Enums

Named Constants — With Caveats

Enums

`enum` declares a set of named constants. There are numeric, string, and `const` flavors — and modern TS code often skips enums entirely.

4 min read Level 2/5 #typescript#enums#oop
What you'll learn
  • Author numeric and string enums
  • Know the runtime cost
  • Use a union of string literals as a modern alternative

enum declares a set of named constants. It’s a TS-only feature — it doesn’t exist in JS.

Numeric Enums

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

const dir: Direction = Direction.Up;
console.log(dir);    // 0

Members get incrementing numbers starting at 0. You can also assign:

enum HttpStatus {
  OK = 200,
  Created = 201,
  NotFound = 404,
  ServerError = 500,
}

String Enums

enum LogLevel {
  Debug = "debug",
  Info  = "info",
  Warn  = "warn",
  Error = "error",
}

const level: LogLevel = LogLevel.Info;

String enums don’t auto-increment. Each member needs a value.

const enum — Inlined at Compile Time

const enum Direction { Up, Down }

const x = Direction.Up;
// compiles to: const x = 0;

No runtime object exists — the values are inlined wherever they’re used. Smaller bundle. The downside: harder to use across module boundaries with isolated modules.

The Runtime Cost (Regular Enums)

enum Color { Red, Green, Blue }

Compiles to a real object — about 12 lines of JS, with reverse mappings for numeric enums (Color[0] === "Red"). For a bundle- sensitive project, that adds up.

The Modern Alternative

For most cases, a union of string literals is simpler:

type LogLevel = "debug" | "info" | "warn" | "error";

const level: LogLevel = "info";
  • Zero runtime cost
  • No reverse-mapping confusion
  • Same compile-time guarantee

Or with as const:

const LogLevel = {
  Debug: "debug",
  Info:  "info",
  Warn:  "warn",
  Error: "error",
} as const;

type LogLevel = typeof LogLevel[keyof typeof LogLevel];
// "debug" | "info" | "warn" | "error"

You get a value-side namespace AND the literal-union type, with no TS-only magic.

When To Use Enums

  • Legacy projects that already use them
  • Numeric protocol constants where the auto-incrementing helps
  • When const enum significantly shrinks generated code

For new code, prefer literal unions or as const objects.

Up Next

Namespaces — the older module-style feature you’ll occasionally encounter.

Namespaces →