Const Enums
In this page:
Basic Const Enum
A const enum is declared with the const modifier and is normally inlined directly into its member value at compile time rather than generating a runtime enum object at all.
Example: Basic Const Enum
const enum Direction {
Up,
Down,
}
const d = Direction.Up;
console.log(d);
Const Enum with Functions
Const enum members work as typed function arguments the same way as normal enum members, but using them avoids creating an actual runtime enum object in the compiled output.
Example: Const Enum with Functions
const enum Color { Red, Green, Blue }
function paint(color: Color) {
return `Painting with color ${color}`;
}
console.log(paint(Color.Green));
Const Enum and Compilation
Const enums are a compile-time-only feature — their members are substituted directly into the generated JavaScript, so there's no object you could inspect or iterate over at runtime the way you can with a regular enum.
Example: Const Enum and Compilation
const enum Size { Small, Medium, Large }
// At compile time, Size.Medium is inlined directly as the number 1.
console.log(Size.Medium);
Const Enum Limitations
Because const enums are meant to be inlined, code shouldn't rely on a runtime enum object existing — this becomes especially important when publishing a library, since some build tools handle const enums differently or disallow them entirely (isolatedModules).
Example: Const Enum Limitations
const enum Mode { Dev, Prod }
// No runtime object exists to iterate over -- Mode.Dev is just inlined as 0.
console.log(Mode.Dev);
When to Use Const Enums
Const enums suit internal applications where the team controls the whole toolchain and predictable inlining behavior is known, reducing the number of emitted enum objects in the final bundle.
Example: When to Use Const Enums
const enum Env {
Development,
Production,
}
console.log(Env.Production);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: