Non-returning functions
A function always throws or terminates without returning.
TypeScript · Const
never represents impossible values and unreachable execution paths. It is especially useful for exhaustive checking of narrowed unions and for functions that throw or never terminate.
never describes an impossible value or an execution path that cannot complete normally. Use it for functions that always throw or terminate, and as an exhaustiveness check after narrowing a union.
type never
function assertNever(value: never): nevernever.never check in a switch default branch catches newly added union members at compile time.never safe as the required type for an impossible state.never; the intended direction is that never can be assigned to other types.never usually simplifies to its other members, so never may disappear from displayed or inferred union types.type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function assertNever(value: never): never {
throw new Error("Unexpected shape: " + JSON.stringify(value));
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "square": return shape.side ** 2;
default: return assertNever(shape);
}
}The default branch is accepted only when narrowing has removed every valid Shape variant.
A function always throws or terminates without returning.
A discriminated union is handled in a switch statement.
A conditional type needs a fallback for unsupported inputs.
never type represent?never represents a value that cannot occur. In a return position, it indicates that a function throws or terminates execution rather than producing a value.
Follow-up: How does it differ from void? void describes a function whose result is not useful or has no value, whereas never means normal completion cannot happen.
never enforce exhaustive switch handling?After narrowing removes every member of a union, TypeScript uses never for the remaining impossible state. Assigning that state to a never parameter lets a default branch verify that all cases were handled.
Follow-up: What happens when a union gains a new variant? The default branch’s argument is no longer never, so the compiler reports the missing case.
never?never is assignable to every type, but no other type is assignable to it except never itself. This makes it suitable as the parameter type of an assertion function used at an unreachable branch.
Follow-up: Why can an assertion function return never too? Because it throws or otherwise never reaches its caller, so the call expression itself has an impossible continuation.
voidunknownNarrowingExhaustiveness checkingConditional typesDiscriminated unions