4 ms·
The string enums don't seem to work the same way as the number enums, there's no 2 way access. For example. enum Test { a } let a = Test.a; let b = Test[ 0
by drk4 9y ago
The string enums don't seem to work the same way as the number enums, there's no 2 way access.
For example.
enum Test { a }
let a = Test.a;
let b = Test[ 0 ]; // isn't available on the string ones
I wonder why its like that.
- RyanCavanaugh 9y agoIf there were a reverse map like for numeric enums, there'd be no way to (at runtime) distinguish a Name from a Value. With a numeric enum you can use typeof Test[x] to figure out if x was a valid Name or valid Value, but this doesn't work for string enums because they're both typeof == 'string'.
- drk4 9y agoThat seems like a much minor situation compared to not being able to reverse map. You could have a situation where you have a string as a code, and then the display name for example, and you can't really do that as is now. This seems more useful than checking for the type (which in a numeric enum is either a number or string, so you would still need to do some work to properly validate it).
- RyanCavanaugh 9y agoIf you want to have the reverse map, you can trivially build it yourself. But if the reverse map did exist (rather, if the map started off as bidirectional, which is the only option on the table), it'd be impossible to properly construct the one-way map.
- drk4 9y agoYou mean because of using the same string for a key/value? I guess I see the potential problem. Anyway just think that it might be a bit confusing to have the enum work slightly different depending on whether its using numbers or strings. It can caught some people off guard.
- DaiPlusPlus 9y agoWhat would be the use-case?
- deleted 9y ago[deleted]
- dsp1234 9y agoInterestingly, 2.3 will spit out what you want (but error on the invalid syntax). var Test; (function (Test) { Test[Test["a"] = "RED"] = "a"; })(Test || (Test = {})); While 2.4 doesn't error out, but omits the inner assignment, thus not allowing the lookup. var Test; (function (Test) { Test["a"] = "RED"; })(Test || (Test = {}));