On this Page
On this Guide
- Lesson 01: What is TypeScript and Why Use It
- Lesson 02: Setting Up TypeScript in Your Project
- Lesson 03: Basic Types and Type Annotations
- Lesson 04: Functions and Type Inference
- Lesson 05: Objects, Interfaces, and Optional Properties
- Lesson 06: Arrays, Tuples, and readonly
- Lesson 07: Union, Intersection, and Literal Types
- Lesson 08: Type Aliases vs Interfaces
- Lesson 09: Working with Enums
What is an Enum?
An enum (short for enumeration) is a way to define a set of named constants. It helps make your code more readable and self-documenting.
Numeric Enums
By default, TypeScript enums are numeric and auto-incrementing:
enum Direction {
Up,
Down,
Left,
Right
}
const move = Direction.Left; // 2
You can override the starting value:
enum Status {
Ready = 1,
Waiting,
Complete
}
Here, Waiting becomes 2 and Complete becomes 3.
String Enums
String enums are more explicit and readable:
enum Role {
Admin = "admin",
User = "user",
Guest = "guest"
}
const access = Role.Admin; // "admin"
They’re especially useful for API data or UI logic where values must match specific strings.
Reverse Mapping in Enums
Numeric enums support reverse lookup:
enum Color {
Red,
Green,
Blue
}
console.log(Color[1]); // "Green"
> 🔒 This doesn’t work with string enums (one-way only).
Enums vs Union Types
Consider a union instead of an enum:
type Direction = "up" | "down" | "left" | "right";
When to prefer enums:
- When using numeric values
- When reverse mapping is needed
- When working with legacy code or class-like structures
When to prefer union types:
- When using strings and simplicity is preferred
- When working with frontend frameworks or form values
Best Practices
- Prefer string enums for clarity
- Avoid
const enumin code shared with external tools (can break builds) - Consider
as constwith union types as an alternative:
const Role = {
Admin: "admin",
User: "user"
} as const;
type Role = typeof Role[keyof typeof Role];
Summary
- Enums create named constants for better semantics and safety
- Use string enums when readability and exact values matter
- Use union types or
as constwhen enums feel too heavy or inflexible
Next up: Type Assertions and Type Casting — telling TypeScript exactly what you mean when inference isn’t enough.