One thing I'm missing in the comments here is that enums are a very early TypeScript feature. They were in there nearly from the start, when the project was still trying to find clarity on its goals and principles.
Since then:
- TypeScript added string literals and unions, eg `type Status = "Active" | "Inactive"`
- TypeScript added `as const`, eg `const Status = { Active: 0, Inactive: 1 } as const`
- TypeScript adopted a stance that features should only generate runtime code when it's on a standards track
Enums made some sense back when TS didn't have any of these. They don't really make a lot of sense now. I think they're effectively deprecated, to the point that I wonder why they don't document them as deprecated.
After almost a decade of TypeScript my recommendation is to not use TypeScript enums.
Enums is going to make your TypeScript code not work in a future where TypeScript code can be run with Node.js or in browser when typings are added to JavaScript[1]
Enums results in runtime code and in most cases you really want type enums. Use `type State = "Active" | "Inactive"` and so on instead. And if you really want an closed-ended object use `const State = { Active: 1, Inactive: 0 } as const`
ENUMs (at least in my experience, which may be dated) had a number of drawbacks that pushed us to this format. I vaguely remember having issues parsing data from the server and/or sending ENUM values to the server but it's been a long time and I've been using this const pattern for around 5 years or so now.
skrebbel ·1 days ago
Since then:
- TypeScript added string literals and unions, eg `type Status = "Active" | "Inactive"`
- TypeScript added `as const`, eg `const Status = { Active: 0, Inactive: 1 } as const`
- TypeScript adopted a stance that features should only generate runtime code when it's on a standards track
Enums made some sense back when TS didn't have any of these. They don't really make a lot of sense now. I think they're effectively deprecated, to the point that I wonder why they don't document them as deprecated.
Show replies
msoad ·1 days ago
Enums is going to make your TypeScript code not work in a future where TypeScript code can be run with Node.js or in browser when typings are added to JavaScript[1]
Enums results in runtime code and in most cases you really want type enums. Use `type State = "Active" | "Inactive"` and so on instead. And if you really want an closed-ended object use `const State = { Active: 1, Inactive: 0 } as const`
All of the examples in the article can be achieved without enums. See https://www.typescriptlang.org/play/?#code/PTAEFEA8EMFsAcA2B...
[1] https://github.com/tc39/proposal-type-annotations
Show replies
ivanjermakov ·1 days ago
Great list of such features: https://www.totaltypescript.com/books/total-typescript-essen...
TS has a great type system, the rest of the language is runtime overhead.
Show replies
joshstrange ·18 hours ago
Show replies
Aeolun ·1 days ago
Show replies