What is a 'const enum' and how does it differ from a regular enum in the compiled output?
Short answer
A const enum is fully inlined at every usage site during compilation and produces NO actual runtime object at all — usages of Direction.Up are replaced directly with the literal value 0 in the emitted JavaScript, resulting in smaller, faster output, at the cost of losing the…
Advertisement
AModel answer
A const enum is fully inlined at every usage site during compilation and produces NO actual runtime object at all — usages of Direction.Up are replaced directly with the literal value 0 in the emitted JavaScript, resulting in smaller, faster output, at the cost of losing the ability to iterate over enum values at runtime.
const enum Direction { Up, Down }
let d = Direction.Up;
// compiles to roughly: let d = 0; -- no Direction object exists at runtimeReal-world example
Using const enums for performance-sensitive, high-frequency code where the small object-creation overhead of a regular enum matters.
Likely follow-ups
- Why are const enums considered risky or discouraged in some bundler/build setups (like with Babel or isolatedModules)?
Related topics