never in Exhaustive Union Checks
What you'll learn: How to use the never type to catch missing union branches at compile time.
The Core Idea
When you work with a union type (like "circle" | "square" | "triangle"), you often want to handle each possible case. TypeScript can help you verify you've covered every case by using never — if a value reaches a point where TypeScript thinks it could be never, but you forgot a case, you'll get a compile-time error.
Think of never as a safety net at the bottom of a cliff. If all your union cases are handled correctly, nothing reaches the net. But if you miss a case, TypeScript "drops" that unhandled value into the net, triggering an error.
How It Works
When you narrow a union type with if checks or a switch statement, TypeScript removes handled cases from the type. After handling all cases, what's left should be never — meaning "nothing is possible here."
If you assign the remaining value to a variable typed as never, TypeScript checks: "Is this really nothing?" If you forgot a case, it's not nothing, and you get an error.
type Shape = "circle" | "square" | "triangle";
function getArea(shape: Shape): number {
if (shape === "circle") {
return 10;
}
if (shape === "square") {
return 20;
}
// Forgot "triangle"!
const exhaustiveCheck: never = shape; // Error: Type 'string' is not assignable to type 'never'
return exhaustiveCheck;
}
If you add the missing triangle case, shape becomes never after all checks, and the error disappears.
Key Takeaway: Use never as an exhaustive check — assign the remaining value after handling all union cases to a never-typed variable to catch missing branches at compile time.