Sub topic 11
Const enums and their trade-offs
A const enum is an enum whose members the compiler replaces with their literal values, so no enum object exists at runtime. This chapter covers what that changes in the emitted JavaScript, the restrictions it adds, and why many projects avoid it.
This chapter assumes you know regular numeric and string enums, including the object they compile to and the reverse mapping on numeric enums. It also assumes you are comfortable with tsconfig.json options and with the idea that a build can use tools other than tsc.
Declaring a const enum
Add const before enum. The syntax for members is the same as for a regular enum.
const enum LogLevel {
Debug = "DEBUG",
Info = "INFO",
Error = "ERROR",
}
function log(level: LogLevel, message: string): void {
console.log(`[${level}] ${message}`);
}
log(LogLevel.Info, "server started");With tsc targeting a modern version of JavaScript, the output contains no LogLevel variable at all:
function log(level, message) {
console.log(`[${level}] ${message}`);
}
log("INFO" /* LogLevel.Info */, "server started");The compiler looked up LogLevel.Info, found the value "INFO", and wrote that value at the use site. It kept the member name as a comment. This is called inlining.
A regular enum would have emitted an object, as shown in the earlier chapter on enum runtime output. The const enum emits nothing for the declaration, and each use costs only the literal.
Constant members only
Inlining requires the compiler to know every value at compile time. That limits what a const enum member may be:
- A numeric or string literal.
- A reference to an earlier member of the same const enum, or of another const enum.
- A parenthesized constant expression, or a unary or binary operator applied to constant expressions, such as
1 << 2orRead | Write.
Members with no initializer are allowed and follow the usual auto-increment rule for numbers.
const enum Permission {
None = 0,
Read = 1 << 0,
Write = 1 << 1,
ReadWrite = Read | Write,
}
function can(granted: Permission, needed: Permission): boolean {
return (granted & needed) === needed;
}
console.log(can(Permission.ReadWrite, Permission.Write)); // true
console.log(can(Permission.Read, Permission.Write)); // falseThe emitted calls pass plain numbers, such as can(3 /* Permission.ReadWrite */, 2 /* Permission.Write */). Bit flags are the case where const enums read best: the names stay in the source, and the output is just integers.
A computed member is rejected:
const enum Broken {
Random = Math.random(), // Error: const enum member initializers must be constant expressions
}A regular enum accepts such a member because it can evaluate the expression when the object is created. A const enum has no object, so there is nowhere to evaluate it.
What you can no longer do
A const enum is not a value you can pass around. The compiler only allows it in a few positions:
- Property access, such as
Permission.Read. - Index access with a string literal, such as
Permission["Read"]. - The right side of an import, an export assignment, or a type query.
Everything that treats the enum as an object fails to compile.
const enum Direction {
Up,
Down,
}
const name = Direction[0]; // Error: a const enum member can only be accessed using a string literal
const all = Object.values(Direction); // Error: const enums can only be used in property or index access expressions
function takesObject(o: object) {}
takesObject(Direction); // Error: same restrictionTwo consequences follow:
- There is no reverse mapping.
Direction[0]is not available, even though the numeric enum equivalent works. - You cannot iterate over members. If you need a dropdown populated from the enum, a const enum cannot supply it. You would have to maintain a separate array by hand, and then the compiler no longer checks that the array is complete.
As types, const enums behave like regular enums. A string const enum is still nominal-like: log("INFO", "x") is rejected, and you must write LogLevel.Info. Numeric const enums still accept arbitrary numbers in older TypeScript versions, the same loophole regular numeric enums had. Since TypeScript 5.0, assigning a literal number that is not a member is an error for both kinds.
The compile-time trade
The benefit of inlining is real but small. You save the enum object, its initialization function (the IIFE shown in the previous chapter), and a property lookup at each use. For a handful of enums this is a few hundred bytes. Modern minifiers also inline many regular enum accesses when they can prove the object is not mutated.
The costs are larger and fall into three groups.
Separate compilation
tsc compiles with the whole program in view. When it sees Permission.Read in a.ts, it can read b.ts where Permission is declared. Many build tools do not work that way. Babel, esbuild, swc, and ts.transpileModule convert one file at a time and cannot resolve a declaration in another file. They also cannot always tell whether an imported name is an enum or a type.
TypeScript names this constraint with the isolatedModules option. With the option enabled:
tscreports an error if you use an ambient const enum (one declared in a.d.tsfile or withdeclare) because the value cannot be known from the current file alone.tsckeeps the enum object in the output even for const enums, as ifpreserveConstEnumswere set, so that code compiled file by file can still import the name at runtime.- Tools that implement their own handling treat a const enum much like a regular enum, with varying degrees of inlining within a single file or a bundle.
So the const keyword stops being a dependable promise about the output. The same source can produce different JavaScript under tsc, esbuild, and Babel. Your type-checking run (tsc --noEmit) and your build run can disagree about whether the enum object exists.
Library boundaries
A const enum exported from a library is inlined into every consumer at the consumer's compile time. The values are copied into the consumer's code. If the library later changes Retry = 3 to Retry = 4, the consumer keeps emitting 3 until it is recompiled. If the library removes a member, an old compiled consumer keeps working against a name that no longer exists.
For this reason, packages that ship .d.ts files should not publish const enums. A consumer using isolatedModules cannot use them at all, because they are ambient const enums in that setting. Use a regular enum, an as const object, or a union in public APIs.
Debugging and runtime inspection
At runtime, 3 is just 3. Logs, stack traces, and debugger watch panels show numbers, and you cannot call Permission[3] in the console to find the name. The /* Permission.ReadWrite */ comments help only when reading the output file, and minifiers strip them.
Related flags
| Option | Effect on const enums |
|---|---|
| `preserveConstEnums` | Still inlines uses, but also emits the enum object. Useful when other code or tools need the object at runtime. |
| `isolatedModules` | Forbids using ambient const enums and keeps the enum object in output. Use it when any non-`tsc` tool compiles your code. |
| `verbatimModuleSyntax` | Requires imports and exports to say whether they are types, which makes per-file tools more predictable. It does not make cross-file inlining possible. |
| `erasableSyntaxOnly` (TypeScript 5.8 and later) | Reports an error for any `enum`, const or regular, because enums emit code that cannot be removed by simply deleting type annotations. |
The last option exists because runtimes such as Node.js can now run TypeScript files by stripping type syntax. Stripping works for annotations and interfaces. It cannot work for enum, which needs generated JavaScript. A project that wants to run its source without a transform step has to avoid both kinds of enum.
How the pipeline differs
The last branch is the dangerous one. If the declaring file was compiled without emitting the enum object, and the consuming file was compiled without inlining, the access fails with a TypeError at runtime even though type checking passed. Enabling isolatedModules exists to prevent this mismatch.
Alternatives that give the same result
You can get most of the benefit of a const enum without the pipeline risks.
For a set of named constants, use a constant object with as const and derive the type:
const Permission = {
None: 0,
Read: 1,
Write: 2,
ReadWrite: 3,
} as const;
type Permission = (typeof Permission)[keyof typeof Permission]; // 0 | 1 | 2 | 3
function can(granted: Permission, needed: Permission): boolean {
return (granted & needed) === needed;
}
console.log(can(Permission.ReadWrite, Permission.Write)); // true
console.log(Object.keys(Permission)); // ["None", "Read", "Write", "ReadWrite"]This version exists at runtime, so you can iterate it and print names. Every tool compiles it the same way, because it is ordinary JavaScript with erasable type syntax. Its type is a union of numbers, so arbitrary numbers are rejected. The cost is a small object in the bundle, and you must write the values yourself (no 1 << 1 in the type, though you can use such expressions in the object and the type will widen to number).
For a set that exists only to restrict a parameter, a plain union of literals needs no runtime code at all:
type LogLevel = "DEBUG" | "INFO" | "ERROR";Here the output has no object, the call sites contain the strings directly, and no build tool can disagree about it. This is the zero-cost option that a string const enum approximates, without the extra rules.
Choosing
| Situation | Suggested choice |
|---|---|
| Application code compiled only by `tsc`, bit flags, no need to enumerate | A const enum is acceptable. |
| Code built by esbuild, swc, Babel, Vite, or any `isolatedModules` setup | Prefer an `as const` object or a union. |
| A public library API | Never publish a const enum. |
| You need to list members or look up a name from a value | Regular enum or `as const` object. |
| Running TypeScript directly with type stripping | Avoid all enums. |
If your codebase already uses const enums and builds correctly, there is no need to migrate. The advice is mainly about new code: the default for new projects should be a union or an as const object, and a const enum should be a deliberate choice you can justify.
Summary of the trade-offs
- A const enum is erased and its members are replaced by literal values at each use site.
- Members must be constant expressions, and the enum can only be used in property or index access.
- There is no reverse mapping and no iteration.
- Whole-program compilation inlines correctly. Per-file tools and library boundaries make the behavior depend on the tool or the version.
isolatedModules,preserveConstEnums, anderasableSyntaxOnlyeach change how far you can rely onconst enum.- A constant object with
as const, or a union of literals, gives you the same type safety with consistent output across tools.
Exercise
A teammate writes const enum Mode { Light = "light", Dark = "dark" } and then adds const modes = Object.values(Mode); to build a settings menu. Does it compile, and what would you change?
Show answer
It does not compile. A const enum can only appear in property or index access, so passing Mode to Object.values is an error, because no Mode object exists at runtime. Replace the const enum with an as const object, const Mode = { Light: "light", Dark: "dark" } as const;, and derive the type with type Mode = (typeof Mode)[keyof typeof Mode];. Then Object.values(Mode) returns the array of values, and Mode.Light still works as before.
Exercise
Your library exports export const enum Retry { Max = 3 } and a consumer compiled with tsc against version 1.0 prints 3 when it uses Retry.Max. You release version 1.1 with Max = 5. What does the consumer do when it upgrades the package without recompiling, and why does isolatedModules also matter here?
Show answer
The consumer still uses 3, because tsc copied the literal into the consumer's output when it was compiled. Its behavior changes only after a recompile. If the consumer enables isolatedModules, using Retry.Max from the library's .d.ts becomes an error, since it is an ambient const enum whose value cannot be resolved from the current file. The fix on the library side is to export a regular enum, an as const object, or a union type instead.