TypeScript Reference ยท tsconfig: Language, Modules and Emit Options
TypeScript preserveConstEnums option
Reference for preserveConstEnums: keep the runtime object for const enum declarations even though uses are inlined, and how it relates to isolatedModules.
A const enum is erased by default: every use like Color.Red is replaced by its literal value (0), and the enum declaration itself produces no JavaScript at all. That is fast and small, but it means there is no Color object at runtime.
preserveConstEnums keeps the declaration in the output, so the object exists even though uses are still inlined. It lets other code, such as a debugger, eval, or a JavaScript caller that imports your library, look values up by name. It is turned on automatically when isolatedModules or verbatimModuleSyntax is set.
const enum Level { Low, High }
Try it
Under the settings of this runner, the first example shows that a plain enum is a real object. The second shows how a const enum is used by value.
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
{ "compilerOptions": { "preserveConstEnums": true } }
| Name | Description |
|---|---|
preserveConstEnums |
Emit the enum object for const enum declarations. Uses are still replaced by their values. Default false (but implied by isolatedModules). |
Usage notes
- Without the option, a const enum can only be accessed through literal member names (
Level.Mid,Level["Mid"]); usingLevelitself as a value, as inObject.keys(Level), is an error. - A
const enumdeclared in one file and imported in another needs the compiler to see both files; a single-file transpiler (esbuild, Babel, SWC) cannot inline it. That is whyisolatedModulestreats exported const enums with care. declare const enumin.d.tsfiles from libraries is hard to use safely when files compile separately.- Many teams skip
const enumand use plainenum, a union of string literals, or anas constobject. - Emitting the object costs a few bytes but removes surprises for JavaScript consumers.
- Under
erasableSyntaxOnly, enums of both kinds are rejected.