Enums in TypeScript: A Comprehensive Guide
An enum gives names to a set of constants. Instead of scattering magic strings or numbers across your codebase, you define them once and reference them ev...
23 Apr 2024

An enum gives names to a set of constants. Instead of scattering magic strings or numbers across your codebase, you define them once and reference them everywhere.
enum Color {
Red,
Green,
Blue
}
By default, Red is 0, Green is 1, Blue is 2. You can assign custom values if you prefer strings or specific numbers.
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING"
}
Using an enum in a function:
function getColorName(color: Color): string {
switch (color) {
case Color.Red:
return 'Red';
case Color.Green:
return 'Green';
case Color.Blue:
return 'Blue';
}
}
console.log(getColorName(Color.Red));
The trade-off
Enums are convenient, but they're one of the few TypeScript features that emit runtime code. A numeric enum compiles to a reverse-mapping object. A string enum compiles to a plain object.
If you want zero runtime overhead, use a const enum (values get inlined at compile time) or a union type:
type Color = 'Red' | 'Green' | 'Blue';
Union types don't exist at runtime — they're erased during compilation. But you lose the ability to iterate over values or use reverse mappings.
I use enums when I need runtime access to the values. I use union types when I only need compile-time checking. Pick the one that fits your situation.