Never Type
In this page:
Function That Throws
A function that always throws an exception never actually returns a value under any circumstance, so TypeScript can give it the never return type rather than void. This precisely captures that control flow never continues past that function call normally.
Example: Function That Throws
function fail(message: string): never {
throw new Error(message);
}
try {
fail("Something went wrong");
} catch (e) {
console.log((e as Error).message);
}
Infinite Loops
A function containing an infinite loop with no break condition can also be typed as returning never, because execution genuinely never reaches a return statement. TypeScript's control-flow analysis is smart enough to recognize this pattern.
Example: Infinite Loops
function logForever(): never {
let i = 0;
while (true) {
console.log(i);
if (i > 2) throw new Error("stopping demo loop");
i++;
}
}
try {
logForever();
} catch (e) {
console.log("loop ended");
}
Never in Union Types
The never type effectively disappears when combined into a union type, since it represents zero possible values and contributes nothing to what the union could be. This shows up naturally when TypeScript narrows away every case of a union, leaving nothing left.
Example: Never in Union Types
type Combined = string | never; // never contributes nothing
let value: Combined = "hello";
console.log(value);
Exhaustive Checking
never is the backbone of exhaustive checking: a default branch that expects never as its type will produce a compiler error if a new member is added to a union and left unhandled. This turns a missed case into a build-time failure instead of a silent runtime bug.
Example: Exhaustive Checking
type Shape = "circle" | "square";
function area(shape: Shape): number {
switch (shape) {
case "circle":
return 3.14;
case "square":
return 4;
default:
const exhaustive: never = shape;
return exhaustive;
}
}
console.log(area("circle"));
Never vs Void
void and never sound similar but mean very different things: void means a function completes normally without returning a useful value, while never means the function does not complete normally at all, whether by throwing or looping forever.
Example: Never vs Void
function completesNormally(): void {
console.log("Finished, but returns nothing useful");
}
function neverCompletes(): never {
throw new Error("Never returns");
}
completesNormally();
try { neverCompletes(); } catch (e) { console.log("caught"); }
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: