128 comments
skrebbel · 1 days ago
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.

Show replies

msoad · 1 days ago
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`

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

Show replies

joshstrange · 18 hours ago
We alway use this in place of ENUMs:

    export const SMS_TYPE = {
        BULK: 'bulk',
        MARKETING: 'marketing',
        PIN: 'pin',
        SIGNUP: 'signup',
        TRANSACTION: 'transaction',
        TEST: 'test',
    } as const;
    export type SmsType = typeof SMS_TYPE[keyof typeof SMS_TYPE];

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.

Show replies

Aeolun · 1 days ago
I don’t understand all these comments. I use TS enums like I use Java enums and I literally never have issues. What are y’all doing with these?

Show replies