๐ŸŽ“ A1Learner
๐Ÿ”

TypeScript Enums

An enum is a named set of related values. Code reads a member by name instead of a bare number or string.

A numeric enum

The members count from 0 in order. The value 0 maps back to the name Up.

enum Direction {
  Up,
  Down,
  Left,
  Right
}
console.log(Direction.Up);
console.log(Direction[0]);

A string enum

Each member below holds a text value. The log line prints the stored text.

enum Status {
  Open = "OPEN",
  Closed = "CLOSED"
}
console.log(Status.Open);
console.log(Status.Closed);

Example

enum Priority {
  Low,
  High
}
let chosen: Priority = Priority.High;
if (chosen === Priority.High) {
  console.log("High priority chosen");
} else {
  console.log("Low priority chosen");
}

Key points

  • The enum keyword starts an enum.
  • A numeric enum counts from 0 by default.
  • A numeric enum maps a value back to its member name.
  • A string enum holds a text value for each member.
  • Each member of a string enum needs its own text value.

In this example, the Priority enum names two members. The chosen variable stores the High member. The if test compares the stored member with High. The test passes and the first log line runs.

Note

String enums have no mapping from a value back to a name.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What value does the first member of a numeric enum hold by default?