What is the never type?
What is the never type in TypeScript
The never type in TypeScript means:
"this value never exists" or "this function never completes successfully".
It is used to mark impossible cases:
- functions that return nothing and never finish,
- code branches that logically can never run.
Examples of where never is used
1. Functions that throw an error
If a function always throws an exception, it never returns a value,
so its return type is never.
javascript
function throwError(message: string): never {
throw new Error(message);
}2. Functions that never finish (for example, an infinite loop)
javascript
function infiniteLoop(): never {
while (true) {
console.log("Running forever...");
}
}Such a function never returns a value and never finishes execution, so it is never.
3. Exhaustive checks (exhaustive check)
One of the most useful scenarios:
TypeScript uses never to guarantee that all cases are handled in a switch or in if branches.
javascript
type Shape = "circle" | "square";
function getArea(shape: Shape): number {
switch (shape) {
case "circle":
return Math.PI * 2 ** 2;
case "square":
return 4 * 4;
default:
// if a new shape is added later - TS will raise an error
const _exhaustiveCheck: never = shape;
throw new Error(`Unknown shape: ${_exhaustiveCheck}`);
}
}If you later add
type Shape = "circle" | "square" | "triangle", TypeScript will raise an error on the lineconst _exhaustiveCheck: never = shape;because"triangle"is not handled.
never versus other types
| Type | Description |
|---|---|
void | The function returns "nothing", but finishes |
never | The function never finishes (error or infinite loop) |
undefined | The value exists, but is not defined |
null | Intentional absence of a value |
Example for comparison:
javascript
function log(): void {
console.log("Just a log");
}
function crash(): never {
throw new Error("Error!");
}Features of the never type
neveris a subtype of every type, so it can be assigned to a variable of any type:
javascript
let n: never;
// let x: number = n; // allowed- But not the other way around:
javascript
let n: never;
// n = 5; // Error: number is not assignable to never- TypeScript automatically infers
neverin situations where a variable can never have a value:
javascript
function process(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else if (typeof value === "number") {
console.log(value.toFixed(2));
} else {
// value has type never here
console.log(value);
}
}Summary
| Property | Description |
|---|---|
| Type | Primitive |
| Values | None |
| Where used | Errors, infinite loops, impossible branches |
Difference from void | void returns "nothing", never returns "never" |
| Subtype | Assignable to all types, but no type is assignable to it |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.