Type-Safe Switches with Literal Unions
You'll learn how to use switch statements with literal union types to catch missing cases and invalid values at compile time.
The Core Idea
When you switch on a literal union type, TypeScript tracks which cases you've handled. If you forget a case or use an invalid string value, the compiler catches it immediately. This turns runtime bugs into compile-time errors—exactly what TypeScript was designed for.
Think of it like a checklist where TypeScript verifies you've checked every box. Miss one, and the compiler stops you before your code ever runs.
How It Works
When your switch expression has a literal union type, TypeScript knows all possible values. Inside each case, it narrows the type to that specific literal. If you cover all cases, the default branch becomes unreachable (type never).
type Status = "pending" | "success" | "error";
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Loading...";
case "success":
return "Complete!";
case "error":
return "Failed!";
default:
// status is type 'never' here - all cases covered
const exhaustive: never = status;
return exhaustive;
}
}
// Compile error: Argument of type '"loading"' is not assignable
// handleStatus("loading");
If you forget a case, the default branch receives that literal type instead of never, causing a type error. This exhaustiveness check ensures you handle every possible value.
Real-World Value
This pattern shines when working with state machines, action types, or any fixed set of options. Add a new literal to the union later, and every incomplete switch immediately shows a compiler error—no grep needed.
Key Takeaway: Switching on literal unions gives you compile-time guarantees that all cases are handled and no invalid values slip through.