Friday, April 5, 2019

What is the preferred syntax for defining enums in JavaScript?




What is the preferred syntax for defining enums in JavaScript? Something like:



my.namespace.ColorEnum = {
RED : 0,

GREEN : 1,
BLUE : 2
}

// later on

if(currentColor == my.namespace.ColorEnum.RED) {
// whatever
}



Or is there a more preferable idiom?


Answer



Since 1.8.5 it's possible to seal and freeze the object, so define the above as:



const DaysEnum = Object.freeze({"monday":1, "tuesday":2, "wednesday":3, ...})


or




const DaysEnum = {"monday":1, "tuesday":2, "wednesday":3, ...}
Object.freeze(DaysEnum)


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:



let day = DaysEnum.tuesday
day = 298832342 // goes through without any errors



One way to ensure a stronger degree of type safety (with enums or otherwise) is to use a tool like TypeScript or Flow.



Source



Quotes aren't needed but I kept them for consistency.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...