stackademic

The leading education platform for anyone with an interest in software development.

TypeScript Enums

Named constants with numeric or string enum members

Overview

Enums declare a set of named constants. String enums are preferred for readability and debugging. Many codebases use as const objects instead of enums for better tree-shaking and JavaScript output.

Syntax / Usage

// String enum (recommended)
enum Role {
  Admin = 'ADMIN',
  User = 'USER',
  Guest = 'GUEST',
}

function authorize(role: Role) {
  if (role === Role.Admin) return true
  return false
}

// Numeric enum (auto-increment)
enum Priority {
  Low,    // 0
  Medium, // 1
  High,   // 2
}

// const enum — inlined at compile time
const enum Direction {
  Up = 'UP',
  Down = 'DOWN',
}

// Alternative: const object + type
const Status = {
  Idle: 'idle',
  Loading: 'loading',
  Done: 'done',
} as const

type Status = (typeof Status)[keyof typeof Status]

Examples

HTTP methods:

enum HttpMethod {
  Get = 'GET',
  Post = 'POST',
  Put = 'PUT',
  Delete = 'DELETE',
}

function request(url: string, method: HttpMethod) {
  return fetch(url, { method })
}

Map enum to display labels:

const roleLabels: Record<Role, string> = {
  [Role.Admin]: 'Administrator',
  [Role.User]: 'User',
  [Role.Guest]: 'Guest',
}

Common Mistakes

  • Mixing numeric and string enums inconsistently
  • Using enums when a simple union of literals is enough
  • Reverse mapping quirks with numeric enums only
  • Importing const enums across project boundaries with isolatedModules

See Also

unions basic-types type-guards interfaces