TypeScript Enums
Enums define a set of named constants. They’re TypeScript-only — not in JavaScript.
Basic Syntax
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let dir: Direction = Direction.Up;
console.log(dir); // "UP"
Why enums? Type-safe alternative to string constants with autocomplete support.
Numeric Enums
Default enums are numeric with auto-increment:
enum Status {
Pending, // 0
Approved, // 1
Rejected // 2
}
let s: Status = Status.Approved;
console.log(Status[1]); // "Approved" (reverse mapping)
Tip: Use explicit values for clarity: Status = { Pending: 0, ... }.
String Enums
String enums are more readable and don’t have reverse mapping:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
Remember: Prefer string enums — they’re self-documenting in logs and errors.
Const Enums
Const enums are inlined at compile time for performance:
const enum Direction {
Up = "UP",
Down = "DOWN"
}
let dir = Direction.Up; // Compiled to: let dir = "UP";
Tip: Use const enums in library code to reduce bundle size.
Enums with Functions
enum Role {
Admin = "admin",
Editor = "editor",
Viewer = "viewer"
}
function canEdit(role: Role): boolean {
return role === Role.Admin || role === Role.Editor;
}
canEdit(Role.Admin); // true
canEdit(Role.Viewer); // false
Iterating Enums
enum Direction {
Up = "UP",
Down = "DOWN"
}
// Get all values
let values = Object.values(Direction); // ["UP", "DOWN"]
Best Practices
- Prefer string enums over numeric
- Use const enums for performance in libraries
- Keep enums focused — one concept per enum
- Consider literal unions as a simpler alternative
Common Mistakes
- Numeric enums without explicit values are hard to debug
- Mixing numeric and string values in one enum
- Overusing enums when literal unions work fine
- Not handling all enum cases in switch statements