TypeScript
/Intermediate
Const Enums
Definition
A special type of enum that is completely removed during compilation. Its values are inlined directly into the generated JavaScript, resulting in zero runtime footprint.
Explain Like I'm New
A normal Enum creates a real JavaScript object to hold its values, which takes up a tiny bit of space. A Const Enum is a ghost. TypeScript reads it, replaces every usage in your code with the raw string/number, and then deletes the Enum completely before the code reaches the browser.
Real World Example
Using `const enum` in a library to ensure the consumer gets the type safety of an enum without paying any bundle-size penalty.
Common Use Cases
- •Optimizing bundle sizes
- •Performance-critical applications
Interactive Example
// The 'const' keyword makes it a ghost! const enum Status { Active = 1, Inactive = 0 } // TypeScript Code: const userStatus = Status.Active; /* COMPILED JAVASCRIPT OUTPUT: // Notice the Enum object completely disappeared! const userStatus = 1 /* Status.Active * /; */
Interview Questions
basic
- How do you declare a const enum?
intermediate
- What happens to a const enum in the compiled JavaScript?
advanced
- What is the `preserveConstEnums` compiler option?