Const enum

2 snippets in TypeScript

Also written as as const enum

TSTypeScript

const Enums

TS · Enums
Syntax
const enum Name {
  Member = value,
}
Example
const enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

const playerDirection = Direction.Up;
// Compiles to: const playerDirection = "UP";
// No Direction object exists at runtime
Output
// const enums are completely erased - values are inlined at compile time

Note const enums produce zero runtime JavaScript - member accesses are replaced with literal values. However, they have compatibility issues: they cannot be used with --isolatedModules (Babel, esbuild, SWC), and they do not work across declaration files in some setups. Many teams ban them in favor of plain unions.

Union Types as Enum Alternatives

TS · Enums
Syntax
type Name = "value1" | "value2" | "value3";
Example
// Instead of enum:
type Theme = "light" | "dark" | "system";

// Object const pattern for when you need both runtime values and types
const THEMES = {
  Light: "light",
  Dark: "dark",
  System: "system",
} as const;

type Theme2 = (typeof THEMES)[keyof typeof THEMES];
// "light" | "dark" | "system"

function applyTheme(theme: Theme2) {
  document.body.dataset.theme = theme;
}
Output
// Union types achieve the same result without enum's quirks

Note Many TypeScript teams prefer string literal unions over enums for simplicity, full tree-shaking, and compatibility with --isolatedModules. The 'as const' object pattern gives you both runtime values (for iteration/lookup) and a derived type - the best of both worlds.

Frequently asked questions

How does TypeScript handle const enum?
TypeScript covers this with 2 copy-ready snippets on this page. The "const Enums" snippet in TypeScript uses `const enum Name {`.
Which code does the TypeScript example use?
The "const Enums" snippet uses `const enum Name {`, from the Enums section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "const enum"?
Besides "const Enums", this page also shows "Union Types as Enum Alternatives".
Is there anything to watch out for?
Yes. For "const Enums": const enums produce zero runtime JavaScript - member accesses are replaced with literal values. However, they have compatibility issues: they cannot be used with --isolatedModules (Babel, esbuild, SWC), and they do not work across declaration files in some setups. Many teams ban them in favor of plain unions.