Declaring a const enum
You'll learn how to create an enum that TypeScript optimizes away completely during compilation.
What Is a const enum?
A const enum is a special variant of enums that exists only at compile time. When TypeScript transpiles your code to JavaScript, it completely removes the enum declaration and replaces every reference to it with the actual literal value. This makes your output JavaScript smaller and faster.
Think of it like having a helpful assistant who translates your notes into final text, then throws away the notes because they're no longer needed.
Basic Syntax
You declare a const enum by adding the const keyword before enum:
const enum Direction {
Up,
Down,
Left,
Right
}
let move = Direction.Up;
This compiles to:
let move = 0; // Just the number!
Notice the entire Direction enum disappeared from the JavaScript output. TypeScript inlined the value 0 directly.
With String Values
It works the same way with string enums:
const enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE"
}
let current = Status.Active;
Compiles to:
let current = "ACTIVE";
Again, the enum vanishes—only the string literal remains.
Why Use const enum?
Use const enum when you want the type safety and autocomplete benefits during development, but want the leanest possible runtime JavaScript. There's no object created, no lookup cost—just direct values.
Key Takeaway: A const enum is declared with const enum and gets completely inlined during transpilation, leaving only literal values in your JavaScript with zero runtime footprint.