Exhaustive Checks
What
Exhaustive checking ensures that your code accounts for every possible value in a union type.
How
By narrowing a type completely within a switch or conditional block, you can use the never type to verify that no cases were missed:
type Status = "open" | "closed" | "pending";
function handle(status: Status) {
switch (status) {
case "open": return "Handling open";
case "closed": return "Handling closed";
case "pending": return "Handling pending";
default:
const check: never = status; // Error if a new status is added
return check;
}
}
Why
Exhaustive checks make your code “future-proof.” If you add a new member to a union later, TypeScript will automatically flag every place where that union is handled, forcing you to update your logic before the code can be compiled.
Summary
Exhaustive checks turn potential runtime bugs into immediate compile-time errors.