Would the following make the objects fulfil all characteristics that enums have in JavaScript? Something like:
JavaScript
x
13
13
1
my.namespace.ColorEnum = {
2
RED : 0,
3
GREEN : 1,
4
BLUE : 2
5
}
6
7
// later on
8
9
if(currentColor == my.namespace.ColorEnum.RED) {
10
// whatever
11
}
12
13
Or is there some other way I can do this?
Advertisement
Answer
Since 1.8.5 it’s possible to seal and freeze the object, so define the above as:
JavaScript
1
2
1
const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, })
2
or
JavaScript
1
3
1
const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, }
2
Object.freeze(DaysEnum)
3
and voila! JS enums.
However, this doesn’t prevent you from assigning an undesired value to a variable, which is often the main goal of enums:
JavaScript
1
3
1
let day = DaysEnum.tuesday
2
day = 298832342 // goes through without any errors
3
One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.
Quotes aren’t needed but I kept them for consistency.