TypeScript Reference ยท Classes, Enums and Decorators
TypeScript const enums
Reference for TypeScript const enums: values inlined at compile time, no runtime object, the preserveConstEnums and isolatedModules options and why to be careful.
A const enum is an enum whose members are replaced by their literal values wherever they are used. The compiler emits no object for it, so there is no lookup at run time and no reverse mapping. The price is flexibility: you can only access members by name with a literal key, and tools that compile one file at a time cannot always inline across files.
Use it only when you control the whole build. For published libraries and for most application code, a plain enum or a union of literals is the safer choice.
const enum Flag { On = 1, Off = 0, } const x = Flag.On; // compiled to: const x = 1 /* Flag.On */;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
const enum Name { A, B = 5, C = "c".length }
Members must be constant: literals, other constant members, and simple operators on them. A computed member is an error in a const enum.
| Option | Effect |
|---|---|
preserveConstEnums |
Still emit the enum object, though uses are inlined. Useful for debugging or when other code might read the object. |
isolatedModules |
Flags patterns that cannot be compiled file by file. Ambient const enum declarations from another file are the main concern. |
verbatimModuleSyntax |
Implies the same single-file thinking; avoid depending on cross-file inlining. |
Edge cases: you can only index a const enum with a string literal (Code["Ok"]), never with a variable, and you cannot pass the enum itself as a value (Object.values(Mode) is an error).
Usage notes
- Inlined values leave a comment such as
/* Code.Ok */in the emitted JavaScript, which helps when reading output. - A
const enumin a.d.tsfile shipped by a library forces consumers to inline values from the library's version. When the library changes a value, existing compiled code keeps the old one. Libraries should avoid them. - Transpilers that process one file at a time (Babel, esbuild, SWC, Node's type stripping) cannot see a const enum declared elsewhere. Many of them treat
const enumlike a normal enum for that reason; check your tool. - Under
isolatedModules, exporting and using aconst enumacross files is restricted for the same reason. - The speed and size gain is small in practice: one object lookup per use. Measure before choosing it.