Computed Property Names
BrighterScript supports using computed property names for associative array keys via the [expr] bracket syntax, similar to computed property names in JavaScript.
The expression inside the brackets must resolve to a string at compile-time. Currently only enum members (string enums), constants, and string literals are supported.
Currently runtime values, such as variables, are not supported
Enum members
String enum members can be used as computed keys. The enum value is inlined at compile-time.
enum ApiPath
login = "/login"
logout = "/logout"
profile = "/profile"
end enum
sub main()
handlers = {
[ApiPath.login]: loginHandler,
[ApiPath.logout]: logoutHandler,
[ApiPath.profile]: profileHandler
}
end subView the transpiled BrightScript code
sub main()
handlers = {
"/login": loginHandler
"/logout": logoutHandler
"/profile": profileHandler
}
end subNamespaced enums work the same way:
namespace Api
enum Path
login = "/login"
profile = "/profile"
end enum
end namespace
sub main()
handlers = {
[Api.Path.login]: loginHandler,
[Api.Path.profile]: profileHandler
}
end subConstants
String constants can also be used as computed keys.
const KEY_NAME = "displayName"
const KEY_AGE = "displayAge"
sub main()
labels = {
[KEY_NAME]: "Name",
[KEY_AGE]: "Age"
}
end subView the transpiled BrightScript code
sub main()
labels = {
"displayName": "Name"
"displayAge": "Age"
}
end subNamespaced constants work as well:
namespace Config
const PRIMARY_COLOR = "primaryColor"
const SECONDARY_COLOR = "secondaryColor"
end namespace
sub main()
theme = {
[Config.PRIMARY_COLOR]: "#ff0000",
[Config.SECONDARY_COLOR]: "#0000ff"
}
end subMixing computed and regular keys
Computed and regular keys can be freely mixed in the same associative array.
enum Field
title = "title"
end enum
sub main()
data = {
id: 1,
[Field.title]: "Hello World",
["some-meta"]: true
}
end subView the transpiled BrightScript code
sub main()
data = {
id: 1
"title": "Hello World"
"some-meta": true
}
end subString literals
The most basic use case is a string literal in brackets.
sub main()
headers = {
["Content-Type"]: "application/json",
["X-Api-Key"]: "abc123"
}
end subView the transpiled BrightScript code
sub main()
headers = {
"Content-Type": "application/json"
"X-Api-Key": "abc123"
}
end subRestrictions
Only string values are allowed
The expression must resolve to a string value. Numeric enum members and numeric constants are compile-time errors.
enum Direction
up ' integer (value: 0)
down
end enum
const TIMEOUT = 30
sub main()
m.data = {
[Direction.up]: "value", ' error: computed AA keys must resolve to a string value
[TIMEOUT]: "value" ' error: computed AA keys must resolve to a string value
}
end subOnly compile-time constants are allowed
The expression must be resolvable at compile-time. Runtime variables are not allowed.
sub main()
key = "someKey"
m.data = {
[key]: "value" ' error: computed property keys must be a compile-time constant
}
end sub