Skip to content

Enums

Named constants. Useful when you have a fixed set of related values.

By default, values start at 0 and auto-increment:

enum Direction {
  Up, // 0
  Down, // 1
  Left, // 2
  Right, // 3
}

let move = Direction.Up;
console.log(move); // 0

move = "Up"; // Error: can't assign string to Direction
enum Direction {
  Up = 1,
  Down, // 2
  Left, // 3
  Right, // 4
}

Set each value explicitly:

enum HttpStatus {
  OK = 200,
  BadRequest = 400,
  NotFound = 404,
  ServerError = 500,
}

if (response.status === HttpStatus.NotFound) {
  console.log("Page not found");
}

More readable in logs and debugging:

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

console.log(Direction.Up); // "UP"