10

Reading the "recommended way" of dealing with ENUM Type in Javascript, I am still uncertain because I can compare the value with a forged value, while I should compare only to a "enum" type value:

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

 switch( day ){
   case "monday":
     return "Hello"
   case "tuesday":
     return "Hi"
   case "blahblahday":
     return "No"
 }

The strings I made the switch to compare against ("monday", "tuesday", "blahblahday") are totally free from my "enum type: DaysEnum", can be provided by the user and this could lead to some subtle errors not spotted by the interpreter (like typos).

Is there a way to have/lock unique index values of the Enum object?

Community
  • 1
  • 1
Simone Poggi
  • 1,448
  • 2
  • 15
  • 34
  • If you want to avoid mistyping I think you need a good IDE instead of trying to do this with the interpreter. E.g. I got auto-completion by your code `switch (day){ case DaysEnum.m[onday...] }` with webstorm. – inf3rno Aug 17 '16 at 11:39
  • 1
    Thank you, but this is not about mistyping, it's about uniqueness of enum values (read: any string with a particular value could comply to my enum, and that's bad IMHO) – Simone Poggi Aug 17 '16 at 13:36
  • Not **THAT** bad, but a little undesiderable – Simone Poggi Aug 17 '16 at 13:37

1 Answers1

4

A possible solution I found with ES2015 could be through Symbols

http://putaindecode.io/en/articles/js/es2015/symbols/

This way you have the unique "locked" values, like you have in other languages, like Java

 const DAY_MONDAY = Symbol();
 const DAY_TUESDAY = Symbol();

 switch(animal) {
   case DAY_MONDAY:
     return "Hello"
   case DAY_TUESDAY:
     return "Hi"
   //there is no way you can go wrong with DAY_BLAHBLAHDAY 
   //the compiler will notice it and throw an error
 }
Simone Poggi
  • 1,448
  • 2
  • 15
  • 34