Compiler Errors When Adding New Union Members
You'll learn: How TypeScript's exhaustive checking breaks compilation when you add a new variant to a union type, forcing you to handle it.
The Safety Mechanism in Action
When you use the never type in exhaustive checks, TypeScript creates a compiler safety net that activates when your union grows. Think of it like a smoke detector that only goes off when there's actually smoke — adding a new union member is the "smoke" that triggers the alarm.
The moment you extend a union type with a new variant, every exhaustive check in your codebase will fail to compile until you handle that new case. This is exactly what you want — it prevents you from accidentally forgetting to update all the places that process that union.
How It Works
Imagine you have this status union and exhaustive handler:
type Status = "idle" | "loading" | "success";
function handleStatus(status: Status): string {
if (status === "idle") return "Ready";
if (status === "loading") return "Loading...";
if (status === "success") return "Done!";
const _exhaustive: never = status; // All cases handled
return _exhaustive;
}
This compiles perfectly because all three cases are covered. But the second you add a new member:
type Status = "idle" | "loading" | "success" | "error";
The handleStatus function immediately fails to compile. TypeScript shows an error at the never assignment:
Type '"error"' is not assignable to type 'never'.
The compiler is telling you: "You claim to have handled everything, but status could still be "error" at this point — handle it!"
Why This Matters
This compiler error is a feature, not a bug. Without it, you might add "error" to your Status type, deploy your code, and only discover at runtime that some functions don't handle errors properly.
With exhaustive checking, you can't even build your project until every handler acknowledges the new variant. It's compile-time protection against incomplete refactoring.
Key Takeaway: Exhaustive checks with never turn union type additions into compiler errors, ensuring you can't forget to handle new cases anywhere in your codebase.