Hacker News new | ask | show | jobs
by bubblyworld 479 days ago
One thing I find useful about enums is that they can be used as both types and values, which is ergonomic for decorator-based libraries (like class-validator, nestjs, mikro-orm, etc). The best approach I've found in union land is using const assertions and typeof, which I don't love.

Agree with the author that in almost every other way unions are better though... they play much more nicely with the rest of the type system. I find it endlessly annoying that I have to refer to enum members directly instead of just using literals like you can with union types.

1 comments

> One thing I find useful about enums is that they can be used as both types and values

Makes sense. You can emulate that behavior by having an object literal with const assertion AND a union type of the same name derived from the object literal.

Right, yeah - this is what I meant by const and typeof. It's definitely an option, but I'm nervous of relying on the semantics of const like that. But maybe I shouldn't be, it seems pretty idiomatic?

(the typeof part is just so you don't repeat yourself, or did you have something else in mind?)