Lesson 6 of 20

Enums

Numeric Enums

Enums allow you to define a set of named constants. By default, enum members are auto-incremented numbers starting from 0.

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

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

// Custom starting value
enum StatusCode {
  OK = 200,
  NotFound = 404,
  ServerError = 500
}

console.log(StatusCode.NotFound); // 404

String Enums

String enums require you to initialize each member with a string value. They're more readable in debugging and logging.

Example
// String enum
enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let favorite: Color = Color.Green;
console.log(favorite); // "GREEN"

// Using enums in functions
function paint(color: Color): void {
  console.log(`Painting with ${color}`);
}

paint(Color.Red);     // OK
paint("RED");          // Error: string not assignable to Color

Const Enums

Const enums are inlined at compile time, resulting in more efficient JavaScript output.

Example
// Const enum — inlined at compile time
const enum Size {
  Small = "S",
  Medium = "M",
  Large = "L"
}

let shirt = Size.Medium;
// Compiles to: let shirt = "M";

// Alternative: use 'as const' with objects
const ROLES = {
  Admin: "admin",
  User: "user",
  Guest: "guest"
} as const;

type Role = typeof ROLES[keyof typeof ROLES];
// type Role = "admin" | "user" | "guest"