DEV Community

The Dangers of TypeScript Enums

Aaron Powell on May 27, 2020

TypeScript introduces a lot of new language features that are common in statically type languages, such as classes (which are now part of the JavaS...
Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Incidentally, C++ enum work the exact same way (except they can only be assigned to int-based values). Too bad Typescript (apparently) doesn't have something analogous to the C++ enum class, which resists implicit casting.

Collapse
 
stojakovic99 profile image
Nikola Stojaković • Edited

Honestly I don't see the reason for putting non-constant value in enums and it looks like antipattern to me. Can you give an example where that would make sense? I'm genuinely interested.

Collapse
 
wrldwzrd89 profile image
Eric Ahnell

An obvious use case is expressions that optimize to constants during compilation, as in the bitwise OR of two values example above, because it makes the source code clearer without compromising what enumerations bring to programming.

Collapse
 
stojakovic99 profile image
Nikola Stojaković

Thanks. That reminds me of the constexpr in C++.

Collapse
 
dobis32 profile image
Scott VanderWeide

Perhaps a given scenario where the non-constant value can easily be computed? There's probably a better way of handling that kind of scenario that doesn't involve a enum; I can't imagine using a non-constant value is considered best-practice.