TypeScript Course
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?

Flash Cards

Question

What happens in the compiled JS?

Click to reveal answer
Answer

The enum declaration entirely vanishes. Any place you typed `Direction.Up`, the compiler literally deletes that text and hardcodes the number `0` in its place.

Question

What is preserveConstEnums?

Click to reveal answer
Answer

If true in `tsconfig.json`, TypeScript will still inline the values everywhere, but it will ALSO generate the actual Enum object. This is useful if you are building a library and need external non-TS JS files to be able to access the Enum object.