Skip to main content

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 line const _exhaustiveCheck: never = shape; because "triangle" is not handled.


never versus other types

TypeDescription
voidThe function returns "nothing", but finishes
neverThe function never finishes (error or infinite loop)
undefinedThe value exists, but is not defined
nullIntentional 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

  1. never is 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
  1. But not the other way around:
javascript
let n: never; // n = 5; // Error: number is not assignable to never
  1. TypeScript automatically infers never in 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

PropertyDescription
TypePrimitive
ValuesNone
Where usedErrors, infinite loops, impossible branches
Difference from voidvoid returns "nothing", never returns "never"
SubtypeAssignable to all types, but no type is assignable to it

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.