TypeScript ยท Chapter 9 of 44

TypeScript Enums

An enum is a way to define a set of named constants, making code more readable than using raw numbers or strings for a fixed list of options. TypeScript supports numeric enums and string enums.

Enums are especially useful for representing things like directions, statuses, or roles, where there is a small, known set of valid values.

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

Numeric enums

By default, enum members are assigned increasing numbers starting at 0, unless you specify your own starting value or explicit values for each member.

String enums

String enums assign a specific string value to each member, which can make debugging easier since the value itself is readable in logs.

Example 1 (typescript)
enum Direction {
  Up,
  Down,
  Left,
  Right,
}
let move: Direction = Direction.Up;
console.log(move);
Output
0

Up is the first member, so it is assigned the numeric value 0 by default.

Example 2 (typescript)
enum Status {
  Active = "ACTIVE",
  Inactive = "INACTIVE",
}
let current: Status = Status.Active;
console.log(current);
Output
ACTIVE

String enums give each member a specific, readable string value.

Key points

  • Enums define a fixed set of named constant values.
  • Numeric enums default to 0, 1, 2, ... unless customized.
  • String enums assign explicit readable string values.
  • Enums make code more descriptive than raw magic numbers or strings.
๐Ÿ’ก Note: For simple cases, a union of string literal types is often preferred over enums in modern TypeScript code.

๐Ÿ“ Quick Quiz

1. What is the default value of the first member in a numeric enum?

2. What kind of value does a string enum member hold?

3. Why use enums?