GGistDev

Enums in TypeScript

Enums provide named sets of constants. Prefer union literal types for many cases; enums remain useful for interop.

Numeric enums

enum Status {
  Idle,        // 0
  Loading = 2, // 2
  Error        // 3
}
const s: Status = Status.Idle;

Numeric enums have reverse mapping at runtime: Status[0] === "Idle".

String enums

enum Direction { Up = "up", Down = "down" }

No reverse mapping; values are stable across compilers.

Const enums (caution)

const enum Flag { A = 1, B = 2 }
const f = Flag.A | Flag.B;

Inlined at emit time. May cause tooling/interop issues unless preserveConstEnums is set; prefer unions when possible.

Alternatives: union literals

type DirectionU = "up" | "down";
function move(dir: DirectionU) {}
  • No runtime artifact
  • Plays well with narrowing and template literal types

Interop scenarios

  • When consuming existing JS that expects numeric constants, enums can be handy
  • For public APIs and libraries, union literals are usually more ergonomic

Summary

  • Use string or numeric enums when you need a runtime object or interop
  • Prefer union literal types for simplicity and type‑level power