constenumDirection{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.
// Instead of enum:typeTheme="light"|"dark"|"system";// Object const pattern for when you need both runtime values and typesconstTHEMES={Light:"light",Dark:"dark",System:"system",}asconst;typeTheme2=(typeofTHEMES)[keyoftypeofTHEMES];// "light" | "dark" | "system"functionapplyTheme(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.