TypeScript Tutorial · Classes and Enums · Lesson 15 of 25

TypeScript Enums

Numeric and string enums — and why union types are often a better choice.

Enums

An enum defines a set of named constants:

Example 1Try it yourself
enum Direction {
  Up,
  Down,
  Left,
  Right,
}
enum Role {
  Admin = "ADMIN",
  Editor = "EDITOR",
}

const move: Direction = Direction.Left;
console.log(move, Direction[move]);
console.log(Role.Admin, Object.values(Role));

Output

2 Left
ADMIN [ 'ADMIN', 'EDITOR' ]

Numeric enums get a reverse mapping (Direction[0] === "Up"); string enums don't.

Unions vs enums

Unlike most TypeScript features, enums generate runtime JavaScript code and can surprise you (numeric enums accept any number in older TypeScript versions). Many teams prefer a union of string literals, optionally with a constant object:

Example 2Try it yourself
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number];   // "admin" | "editor" | "viewer"

function canEdit(role: Role): boolean {
  return role === "admin" || role === "editor";
}
console.log(ROLES.map((r) => `${r}: ${canEdit(r)}`).join(", "));

Output

admin: true, editor: true, viewer: false

Test yourself with the TypeScript enums output puzzle.

Test yourself

Do string enums have a reverse mapping from value to name?

  1. Yes
  2. No
Show answer

Answer: No

Practice next