Re:TypeScript 3.6
by benatkin on Wednesday August 28, 2019 @06:42PM
(#20824817)
I'm aware of this capability in TypeScript, which is why I specified integer enums instead of just calling it an enum. However, integer enums are still an option, and with TypeScript it would be easy to use an integer as a micro-optimization, which could be a pain if JSON gets exported and the person looking at it doesn't know what the numbers mean.
[ Parent
| on HN ]
Ah, I thought you were referring to an integer taking the place of an enum, which is a terrible practice that for some reason is more common than you'd think. I'm not too sure what you mean by 'micro-optimization' here, these kind of languages are so high level that the term 'optimisation' really doesn't apply. Regarding the JSON serialisation point: The internal representation of an enumerated type would probably depend on the needs of its serialisation medium. If it's going in a binary file, then an integer is probably your best bet. If it's going into a database, you might not have that limitation. This all depends on the scenario. As long as you're referencing the enum by its proper handle, that is.
I was thinking of it as a storage optimization. "inactive" is going to take more storage than the number 2, both serialized and deserialized. Might seem like a bigger deal than the difference in CPU usage.
If you use a const enum in TypeScript it gets transpiled down to just the plain integer or string without any additional overhead. It just means you can't use a variable to get a value from the enum e.g. State[ currentState ] - which I'm not sure is a good pattern to use anyway.