Enums as Types
What You'll Learn
You'll learn how to use an enum's name as a type annotation, restricting variables to only accept valid enum members and gaining compile-time safety.
The Core Idea
In TypeScript, an enum isn't just a collection of constants—the enum name itself becomes a type. When you declare a variable with an enum type, TypeScript ensures you can only assign values that are members of that enum. This gives you autocompletion, prevents typos, and catches invalid assignments at compile time.
Think of it like a restaurant menu. If you tell the waiter "I'll have something from the dinner menu," you're constraining your choice to only those items. Similarly, typing a variable as MenuEnum means it can only hold values from that specific enum.
Using Enum Names as Types
enum Direction {
North,
South,
East,
West
}
// The enum name becomes a type
let currentDirection: Direction;
currentDirection = Direction.North; // ✓ Valid
currentDirection = Direction.East; // ✓ Valid
// currentDirection = 5; // ✗ Error: Type '5' is not assignable to type 'Direction'
// currentDirection = "North"; // ✗ Error: Type 'string' is not assignable
With string enums, the same pattern works:
enum Status {
Pending = "PENDING",
Active = "ACTIVE",
Archived = "ARCHIVED"
}
function updateStatus(newStatus: Status): void {
// Only accepts Status enum members
}
updateStatus(Status.Active); // ✓ Works
// updateStatus("ACTIVE"); // ✗ Error: expects Status type, not raw string
Key Takeaway: Using an enum's name as a type ensures compile-time safety—only valid enum members can be assigned, preventing runtime errors from invalid values.