Exhaustiveness in Switch Statements
You'll learn: How to use the assertNever helper in the default case of a switch statement to force TypeScript to verify you've handled all possible union variants.
The Core Idea
When working with discriminated unions, you want TypeScript to yell at you if you forget to handle a case. The assertNever helper function (which you learned in the previous lesson) becomes incredibly powerful when placed in the default case of a switch statement. If TypeScript can reach that default case with a non-never type, it means you've missed a branch—and the code won't compile.
Think of it like a safety net with an alarm: if any value "falls through" to the default case, the alarm goes off at compile time.
Placing assertNever in the default Case
Here's the pattern:
type Status = "pending" | "success" | "error";
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${value}`);
}
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Loading...";
case "success":
return "Done!";
case "error":
return "Failed!";
default:
// If we've handled all cases, status is now type never
return assertNever(status); // ✅ No error—all cases covered
}
}
Now imagine you add a new status but forget to handle it:
type Status = "pending" | "success" | "error" | "canceled";
function handleStatus(status: Status): string {
switch (status) {
case "pending":
return "Loading...";
case "success":
return "Done!";
case "error":
return "Failed!";
default:
return assertNever(status); // ❌ Error! status is type "canceled"
}
}
TypeScript produces a compile error because status in the default case is "canceled", not never. You must add the missing case.
Why This Works
By the time execution reaches the default case, TypeScript has narrowed status through control flow analysis. If you've handled every possible variant, the type becomes never (an empty set). If you've missed one, that variant's type remains, triggering a type mismatch when passed to assertNever.
Key Takeaway: Place assertNever in the default case of your switch statements to guarantee compile-time errors when you add new union variants but forget to handle them—turning potential runtime bugs into build failures.