Hacker News new | ask | show | jobs
by zdragnar 480 days ago
Seeing posts like these, I often feel alone preferring enums to string unions.

There are certain situations where refactoring a string in a union will not work but refactoring an enum will. I don't want to type strings when, semantically, what I want is a discrete type. I don't even care that they become strings in JS, because I'm using them for the semantic and type benefits, not the benefits that come with the string prototype.

4 comments

That precisely one of my problem with enum: almost all TS type is structural typing, why have this exception enums being nominal typing?
Classes aren't interchangable, excepting using a child when a parent is called for.

Likewise, enums represent a discrete and unique set. The fact that there is either a number or a string used under the hood is irrelevant.

I imagine using numbers or strings was useful for interop with vanilla JS (where JS needs to call a TS function with an enum as an argument), so it makes sense to use it instead of Symbols, which is what I typically pretend enumd are.

And to add to the confusion Template Types let you compare enums as if they were strings.
A year back or so I sat down, read through all the pros and cons including many HN posts just like this one, and I came to the same conclusion. Default to string enums. If I really need to iterate over the keys (generally an antipattern anyway), possibly refactor it into a const object literal. Never use const enums, number enums, or implicit enums.
Interesting point about semantics. I wish there was a way to get the best of both - discrete type (correct semantics) but one that is auto inferred from literals in contexts where the type system expects it (ergonomics of use). Perhaps there are good reasons that doesn't work though, I haven't thought through it much =P
You’re not alone! I’ve given up the preference on team projects for pragmatic reasons, but the semantics of (string) enums are still my personal preference.