Exhaustiveness in If-Else Chains
What you'll learn: How to use never to catch missing cases in if-else chains, just like you do in switch statements.
Why If-Else Chains Need Exhaustiveness Checks
You've seen how switch statements can verify that all union members are handled. But sometimes you'll use if-else chains instead of switch statements—maybe because the logic is cleaner or you're checking multiple conditions. TypeScript's never type works here too, ensuring you don't forget a case.
The Pattern
After your if-else chain, assign the union variable to never. If all cases are handled, the variable's type has been narrowed to never (an empty type). If you forgot a case, TypeScript will complain because the remaining type isn't assignable to never.
type Status = "loading" | "success" | "error";
function handleStatus(status: Status): string {
if (status === "loading") {
return "Please wait...";
} else if (status === "success") {
return "Done!";
} else if (status === "error") {
return "Something went wrong";
} else {
// This check ensures all cases are handled
const exhaustive: never = status;
return exhaustive;
}
}
What Happens When You Forget a Case
If you remove one of the if-else branches (say, the "error" check), the else block receives status with type "error", not never. TypeScript will error: Type 'string' is not assignable to type 'never'.
This forces you to handle the missing case.
Using assertNever for Better Errors
Pair this pattern with your assertNever helper for clearer error messages:
function assertNever(value: never): never {
throw new Error(`Unhandled value: ${value}`);
}
function handleStatus(status: Status): string {
if (status === "loading") {
return "Please wait...";
} else if (status === "success") {
return "Done!";
} else {
return assertNever(status); // Compile error if status isn't never
}
}
When to Use This
Use this pattern when:
- Your logic is clearer with if-else than switch
- You're checking discriminated unions with complex conditions
- You want the same safety guarantees as switch exhaustiveness
Key Takeaway: Assigning your union variable to never in the final else block forces TypeScript to verify you've handled every possible case in your if-else chain, catching bugs at compile time.