Skip to main content

TypeScript Enums

An enum is a special kind of "class" that holds a group of constants — values that cannot be changed.

Enums come in two flavors: string enums and numeric enums.

We start with numeric enums.


Numeric Enums - Default

By default, an enum gives its first member the value 0 and adds 1 for each member after it.

Example

North is 0, East is 1, and so on. Assigning the plain string 'North' to a variable of the enum type is a compile error — only the enum members are valid values.

Prompt
Show that a numeric enum starts at 0 by default, and that a plain string is not a valid enum value. Declare an enum CardinalDirections with members North, East, South, West (no explicit values), assign CardinalDirections.North to a variable and log it (0), then assign the string 'North' to that same variable so the compiler reports that a string is not assignable to the enum type.
Output: TypeScript file and captured output

Numeric Enums - Initialized

You can give the first member a starting value. The following members then count up from that value automatically.

Example

North is set to 1, so East becomes 2, South 3 and West 4.

Prompt
Show that a numeric enum can start from a chosen value and keep auto-incrementing from there. Declare an enum CardinalDirections where North is set to 1 and East, South, West get no explicit value, then log CardinalDirections.North (1) and CardinalDirections.West (4).
Output: TypeScript file and captured output

Numeric Enums - Fully Initialized

You can also give every member its own unique number.

When you do that, no value is incremented automatically — each member keeps exactly the number you wrote.

Example

Every HTTP status code is written out explicitly, so StatusCodes.NotFound is 404 and StatusCodes.Success is 200.

Prompt
Show a numeric enum where every member has its own explicit value, so nothing is auto-incremented. Declare an enum StatusCodes with NotFound = 404, Success = 200, Accepted = 202 and BadRequest = 400, then log StatusCodes.NotFound (404) and StatusCodes.Success (200).
Output: TypeScript file and captured output

String Enums

Enums can also hold string values.

String enums are more common than numeric ones, because the values are easier to read and make the intent clearer.

Note: Technically you can mix string and numeric values in one enum, but it is recommended not to do so.

Example

Each member is given a string value, so logging CardinalDirections.North prints the text North rather than a number.

Prompt
Show an enum whose members hold string values instead of numbers. Declare an enum CardinalDirections where North, East, South and West are each set to their own name as a string, then log CardinalDirections.North ("North") and CardinalDirections.West ("West").
Output: TypeScript file and captured output