Exhaustiveness Without Runtime Code
What you'll learn: How to enforce exhaustive union handling at compile time using never type assignments, without including any runtime helper functions like assertNever.
The Compile-Time-Only Approach
In the previous lesson, you saw assertNever() as a runtime function that validates exhaustiveness. But what if you want the compiler to yell at you when you forget a case, without adding any runtime overhead?
The trick is to assign your value to a never type variable. If TypeScript successfully narrows your union to never (meaning all cases were handled), the assignment succeeds. If cases remain, the compiler throws an error at compile time — and the assignment line never needs to run.
The Pure Type-Level Pattern
type Status = "pending" | "success" | "error";
function handleStatus(status: Status): string {
if (status === "pending") {
return "Loading...";
}
if (status === "success") {
return "Done!";
}
// Exhaustiveness check: no runtime code needed
const _exhaustive: never = status; // Error if 'error' case missing!
return _exhaustive;
}
If you remove the status === "success" branch, TypeScript immediately flags status as "success" | "error" at the assignment line, and that cannot be assigned to never. Compile error.
Why This Works
Think of it like a "type trap" at the end of your logic. If any union member slips through your conditions, it crashes into the never wall. The compiler sees this impossible state and stops you immediately — all before a single line runs in production.
Key Takeaway: Assigning leftover union values to never type variables catches non-exhaustive handling at compile time with zero runtime footprint, making it the leanest exhaustiveness check available.