TypeScript never Type
The never type represents the type of values that never occur. It is a "bottom type", meaning it is a subtype of every other type, but no type is a subtype of never (except never itself).
1. When is never used?
TypeScript infers never in specific situations where a valid value can never exist or be returned.
A. Functions that throw errors
If a function always throws an exception, it never returns a value.
function throwError(message: string): never {
throw new Error(message);
}
B. Infinite Loops
If a function has an infinite loop and never reaches an end point, its return type is never.
function infiniteLoop(): never {
while (true) {
// do something
}
}
2. Exhaustiveness Checking
The most practical use of never is ensuring you have handled all possible cases in a union type (e.g., in a switch statement).
type Shape = "circle" | "square";
function getArea(shape: Shape) {
switch (shape) {
case "circle":
return Math.PI * 10; // simplified
case "square":
return 100;
default:
// If 'shape' is "circle" or "square", we never reach here.
// 'shape' is narrowed to 'never' here.
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
If you later add "triangle" to Shape but forget to update the switch case, TypeScript will error at const _exhaustiveCheck: never = shape because shape will be "triangle" (which is not assignable to never).
3. never vs void
void: The function returns, but it returns "nothing" (technicallyundefinedin JavaScript).never: The function never returns. It crashes or loops forever.
// Returns undefined
function log(msg: string): void {
console.log(msg);
}
// Doesn't return at all
function fail(msg: string): never {
throw new Error(msg);
}
4. never in Intersections
Because never is a subtype of everything, intersecting anything with never results in never. This is useful for filtering types in conditional types.