Sub topic 3
TypeScript `never`: The Type With No Values
Assume you know type annotations, union types, and JavaScript control flow. This chapter focuses on never, which represents a value that cannot exist.
`never`: the type with no values
never is the bottom type of TypeScript's type system. No value can have the type never. TypeScript uses it for code that cannot finish normally, such as a function that always throws:
function fail(message: string): never {
throw new Error(message);
}
function getPort(value: string | undefined): string {
if (value === undefined) {
return fail("PORT is required");
}
return value;
}After fail runs, execution cannot continue. TypeScript therefore knows that value is a string at the final return.
A function with an infinite loop can also return never:
function waitForever(): never {
while (true) {
// Keep waiting.
}
}Exhaustive checks with `assertNever`
A discriminated union has a shared property that identifies each variant. An assertNever helper checks that every variant appears in a switch:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: 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.size ** 2;
default:
return assertNever(shape);
}
}If you later add a "triangle" variant but forget its case, shape in the default branch becomes a triangle rather than never. The compiler reports an error.
How `never` behaves in types
never disappears from unions because adding no possible values changes nothing. It makes an intersection impossible when combined with incompatible types. Conditional types often use it to remove union members.
type Without<T, U> = T extends U ? never : T;
type Remaining = Without<"a" | "b" | "c", "a">; // "b" | "c"
type Same = string | never; // string
type Impossible = string & number; // neverChoosing between `any`, `unknown`, and `never
| Type | Meaning | Typical use |
|---|---|---|
| `any` | Skip type checking | Temporary migration boundary |
| `unknown` | A value exists, but its type is unverified | JSON, APIs, and external input |
| `never` | No value can exist or execution can continue | Impossible states and exhaustive checks |
Prefer unknown when you need to inspect untrusted data. Use any only when containing or migrating unsafe code. Use never to describe impossible values and enforce complete control flow.
Exercise
What compiler error should appear after adding a "triangle" member to Shape without adding a case?
Show answer
The call assertNever(shape) fails because shape is "triangle", not never.