Settings

Theme

In Defence of TypeScript Enums

yazanalaboudi.dev

19 points by romellem 9 months ago · 6 comments

Reader

TheCycoONE 9 months ago

I think the author missed that we are criticising typescript's enum implementation not the concept of enums in general.

They transcribe to something better defined in javascript. Typescript itself akwardly sits on the fence of almost entirely erasable and some decisions only make sense if that was the goal, like import files having a js rather than the ts extension that would point to the file in source.

Enums become javascript objects in a very leaky abstraction full of footguns. There are plenty of articles that cover these and this author seems to have written them off as 'not holding it right' but a good language feature fits in the hand naturally to stretch the analogy.

miningape 9 months ago

This is the problem with typescript enums, they're close enough to "normal" enums in other "real" languages that there aren't any hard edges at first glance. Luring you in with a false sense of comfort and familiarity.

Then abstraction starts leaking everywhere because it's trying to bridge between typescript and javascript and you start wishing you had either made an object (pure JS) or a literal union (pure TS).

koshdim 9 months ago

Nice article, clearly defines the scope for enums and why it is so in TS. I had the same feeling and use enums a lit less than in C#, because of mentioned limitations, but they're still useful for right purpose

tengbretson 9 months ago

`if (color === "Red") {`

This counter example against using unions of literals would result in a compiler error ts(2367). Which only furthers the argument for using unions of literals instead.

paulddraper 9 months ago

> Enums Are Meant To Be Symbolic

And yet you can’t use symbols [1].

Author gives a valiant effort, but is defending the indefensible.

[1] https://github.com/microsoft/TypeScript/issues/18408

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection