-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bidirectional (TypeScript-style) enums #8
Comments
The enum design in this proposal is bidirectional, but requires the use of an enum API to accomplish this. Having an external API is more reliable for string-valued enums like this: enum E {
red = "blue",
blue = "green"
} In TypeScript, this results in an enum that is not bidirectional. Instead you would do the following (using your example above): console.log(FatAnimals.Pig); // number 2
console.log(Enum.getName(FatAnimals, 2)); // string "Pig" |
Huh, learn something new every day - I actually wasn't aware TypeScript allowed enumeration members to be anything other than ints (as in C), so them allowing string-valued keys is news to me. I can see why your example wouldn't be bidirectional in TS. 😄 I definitely agree having an explicit API for this is much more flexible and robust; I dislike the verbosity of a function call here (I'd prefer some kind of operator I think) but realistically doing a value->key mapping is probably not a common enough thing for it to matter in the grand scheme of things. I only really foresee it being done for serialization purposes. To be honest, I'll just be happy if |
🚲🏚 A bit a bikeshedding here, but looking at that API listing, since I would almost expect something called "getName" to return the name of the enumeration rather than a specific key. |
Perhaps |
Can
enum
be bidirectional like in TypeScript? For example:This is nice for serialization as it gives you an easy way to serialize the human-readable enum key while passing it around as a number internally. Admittedly this is only useful for
Number
-based enums, and the use case in question is solved by using aString
-based enum, but numbers are more optimizer-friendly (not all JS engines intern strings so string comparison can be more expensive than number comparison).The text was updated successfully, but these errors were encountered: