Creating an assertNever Helper
You'll learn how to write a reusable utility function that both throws errors at runtime and serves as a compile-time exhaustiveness check.
Why You Need a Helper
In the previous lesson, you learned the inline pattern of using never to check exhaustiveness in switch statements. But writing that logic over and over gets tedious. More importantly, you might want to throw a meaningful error message if somehow unhandled code paths execute at runtime.
The solution is a dedicated assertNever helper function.
The Helper Function Pattern
Here's the standard implementation:
function assertNever(value: never): never {
throw new Error(`Unhandled case: ${value}`);
}
What's happening here:
- Parameter typed as
never: This means TypeScript expects no valid value can ever be passed. If you can pass something, TypeScript flags it as an error. - Return type
never: The function never returns normally—it always throws. - Runtime safety: If somehow a value slips through (maybe due to unsafe casts elsewhere), you get a clear error message instead of silent misbehavior.
Using assertNever in Practice
type Status = "idle" | "loading" | "success" | "error";
function handleStatus(status: Status) {
switch (status) {
case "idle":
return "Waiting to start";
case "loading":
return "In progress";
case "success":
return "Completed";
case "error":
return "Failed";
default:
return assertNever(status); // status is type never here
}
}
If you later add "cancelled" to Status without updating handleStatus, TypeScript errors at the assertNever call because status is now "cancelled", not never.
Why This Helper Matters
Think of assertNever as a double safety net: it catches missing cases at compile time and provides a runtime safeguard with a helpful error message. It's especially valuable in large codebases where union types might evolve over months or years.
Key Takeaway: The assertNever helper combines compile-time exhaustiveness checking with runtime error throwing, making your exhaustiveness checks both safer and more maintainable.