Skip to main content

numeric and string enums enumerations in TypeScript

ยท 2 min read

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 enums enums.

For example, let's define an enum for the direction of a compass:

enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH;

The advantage of Enums is that we can define constants with names, and we can clearly express intent or create a differentiated set of use cases

TS supports numeric and string enums enums, let us start with the numeric enums:

enum Direction {
Up = 1,
Down,
Left,
Right,
}

This is an enumeration of numbers, and we initialize Up to 1, and the rest will automatically grow from 1.

Of course, there is no need to initialize, as follows

enum Direction {
Up,
Down,
Left,
Right,
}

The default is to increment from 0

So how do you use enumerations?

The answer is that enumeration members are accessed by enumeration properties, and enumeration types are accessed by enumeration names. For example, when we talk about types:

enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH;

String enumerationโ€‹

In a string enumeration, each member must be initialized with either a string literal or another string enumeration member. Such as:

enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}

String enumerations serialize well because string enumerations have no self-growing behavior. If you are debugging and have to read the runtime value of a numeric enumeration, the value is usually hard to read and does not express useful information, whereas string enumerations allow you to provide a run-time value that is meaningful and readable, independent of the enumerator's name.

You may be wondering if strings and numbers can be mixed. Note that enumerations do mix string and number members, but this is generally not recommended.