Enums

Enums allow developers to define a set of named constants, making code more readable and self-documenting.

1. Numeric Enums

By default, numeric enums auto-increment their values starting from 0:

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

let userDirection: Direction = Direction.Up; // Value is 0

2. String Enums

String enums give meaningful runtime values in log outputs and database records:

enum UserRole {
  Admin = "ADMIN",
  Editor = "EDITOR",
  Viewer = "VIEWER"
}

function checkAccess(role: UserRole) {
  if (role === UserRole.Admin) {
    console.log("Full access granted!");
  }
}

3. `const` Enums (Zero Overhead in Compiled JS)

Standard enums generate extra JavaScript object code. const enum completely eliminates runtime objects by inlining enum values directly:

TypeScript Code:
const enum Status {
  Active = 1,
  Inactive = 0
}

let current = Status.Active;
Compiled JavaScript:
// Inline compiled value! No JS object overhead.
var current = 1;

Next Up

Master Interfaces in TypeScript: defining object structures, optional properties, and interface extension.

Next Lesson: Interfaces →