Enums
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
Numeric enums
enum Direction {
Up = 1,
Down,
Left,
Right,
}
Above, we have a numeric enum where Up
is initialized with 1
. All of the following members are auto-incremented from that point on. By default enums start numbering their members starting at 0
.
String enums
In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
Downsides of Enums
There is some discussion about whether you should ever use enums in the first place, because they have some weird runtime behavior.
See the following videos for reference: