The never Type
The type of values that should never occur.
The Impossible Type
never is TypeScript's bottom type. It represents a state that is mathematically impossible to reach.
A function that always throws an error or runs in an infinite loop has a return type of never. More importantly, never is used to represent the remaining possibilities when you have exhausted all other options in a union type.
Exhaustive Checking
The true power of never comes from exhaustive type checking. Imagine you have a discriminated union of shapes (Circle | Square). You write a switch statement that handles both.
What happens when a teammate adds Triangle to the union six months later, but forgets to update your switch statement? If you assign the unhandled shape in the default block to a never variable, TypeScript will instantly throw a compiler error because Triangle cannot be assigned to never.
Using never to catch bugs
You enforce exhaustiveness by creating a dummy variable typed as never in your default case.
typescript
type Shape = "circle" | "square";
function getArea(shape: Shape) {
switch (shape) {
case "circle": return Math.PI;
case "square": return 4;
default:
// If shape is fully handled, 'exhaustiveCheck' compiles.
// If 'triangle' is added later, TS throws an error here.
const exhaustiveCheck: never = shape;
return exhaustiveCheck;
}
}
Try it
Watch what happens when a new Triangle type is added to the system, but the developer forgets to update the switch statement. The never check catches it instantly.
"triangle" to the union...Misses "circle" ... Misses "square" ...
Falls into default block.
Type '"triangle"' is not assignable to type 'never'.
The compiler caught the missing case instantly!
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
neverrepresents values that can never occur, or functions that never return.- It is the ultimate tool for exhaustive checking in
switchstatements. - Assigning an unhandled case to
neverensures the compiler alerts you if you add a new type to a union later.
Done with this concept?
Mark it complete to track your progress. No login needed.