Skip to content
Tutorials Center
My learning

Topics

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.

TypeScript
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.

TypeScript A regular enum exists at runtime

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.

TypeScript A const enum is inlined

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

JSON
{
  "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"]); using Level itself as a value, as in Object.keys(Level), is an error.
  • A const enum declared 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 why isolatedModules treats exported const enums with care.
  • declare const enum in .d.ts files from libraries is hard to use safely when files compile separately.
  • Many teams skip const enum and use plain enum, a union of string literals, or an as const object.
  • Emitting the object costs a few bytes but removes surprises for JavaScript consumers.
  • Under erasableSyntaxOnly, enums of both kinds are rejected.