TypeScript Enums and When to Use Them
Ad
What are Enums?
Enums let you define a set of named constants, making code more readable and intent clearer than magic strings or numbers.
Numeric Enums
enum Direction { Up, Down, Left, Right }
let move: Direction = Direction.Up; // 0
String Enums (Preferred)
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Banned = "BANNED",
}
const s: Status = Status.Active; // "ACTIVE"
Enums vs Union Types
// Often a union is simpler and lighter:
type Status = "active" | "inactive" | "banned";
| Enum | Union | |
|---|---|---|
| Runtime code | Yes | No (erased) |
| Readability | Good | Good |
FAQs
Enum or union type?
Prefer union types unless you need a runtime object. More in our TypeScript guides.
What is a const enum?
An enum inlined at compile time for zero runtime cost.
