Sub topic 10
never: the type with no values
This chapter assumes you know basic TypeScript syntax (annotations, interfaces, union types), how typeof narrowing works, and how to run tsc or use an editor with TypeScript support. Earlier chapters covered any and unknown, the types that sit at the top of the type system. This chapter covers never, the type at the bottom.
What never means
Think of a type as the set of values a variable may hold. string is the set of all strings, and "a" | "b" is a set with two members. never is the empty set. No value has type never, so a variable of that type can never hold anything at runtime.
That makes never the bottom type, and two rules follow from the empty set:
neveris assignable to every type. The empty set is a subset of every set.- Nothing except
neveris assignable tonever. No value can be put into an empty set.
function fromNever(x: never): string {
return x; // OK: never is assignable to string
}
function toNever(): never {
// return "hello"; // error: Type 'string' is not assignable to type 'never'
throw new Error("unreachable");
}The first function compiles because the body can only run if someone passes a value of type never, and no such value exists. TypeScript lets you treat that impossible value as any type you like.
Where never comes from
You rarely write never by hand. Most of the time the compiler produces it. The sources are:
- A function that never returns normally.
- A narrowing step that has ruled out every possibility.
- An intersection of types that cannot overlap.
- A conditional type that filters members out of a union.
- A literal such as
[]with nothing to infer the element type from.
The next sections cover the first three and the last. Conditional types appear in a later chapter.
Functions that never return
A function has return type never when it cannot reach its end. This happens when it always throws, or when it loops forever.
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; // narrowed to string
}Because fail returns never, the compiler knows the if branch cannot continue past the call. After the if, value is string. Without the annotation, fail would not give you that guarantee.
Annotating the return type matters because the compiler infers never for some functions and void for others:
function declared() {
throw new Error("a");
}
const expression = function () {
throw new Error("b");
};
const arrow = () => {
throw new Error("c");
};
type R1 = ReturnType<typeof declared>; // void
type R2 = ReturnType<typeof expression>; // never
type R3 = ReturnType<typeof arrow>; // neverA function declaration with no annotation that only throws is inferred as void. Function expressions and arrow functions are inferred as never. This difference is a historical quirk, and it is the main reason to write : never yourself on any helper meant to stop execution.
never versus void
void and never both describe functions that give you nothing useful, but they mean different things.
| Type | Meaning for a function | Can the call finish? | Assignable to `string`? |
|---|---|---|---|
| `void` | Returns, and the result should be ignored | Yes | No |
| `undefined` | Returns the value `undefined` | Yes | No (under `strictNullChecks`) |
| `never` | Never returns to the caller | No | Yes |
If a function logs a message and returns, use void. If it throws or exits the process, use never. A function that calls process.exit() can be typed never because Node's own typings declare exit that way.
Narrowing down to never
Narrowing removes members from a union as you rule them out. When every member has been removed, what remains is never.
function describe(value: string | number): string {
if (typeof value === "string") {
return "a string";
}
if (typeof value === "number") {
return "a number";
}
return value; // value is never here
}Hovering over value on the last line shows never. This is the mechanism behind exhaustiveness checking, which a later chapter builds into the assertNever helper.
The result is also a warning sign. If you expect a branch to be reachable and your editor shows never there, one of your earlier conditions already covered that case, or the types do not describe the values you think they do.
Impossible intersections
An intersection A & B is the set of values that belong to both A and B. If the two sets share no values, the result is empty.
type C = string & number; // never
type Impossible = { kind: "a" } & { kind: "b" }; // neverThe first case is obvious. The second is subtler. Both object types are fine on their own, but the property kind would have to be "a" and "b" at once. Since TypeScript 3.9, an intersection of object types whose discriminant properties conflict is reduced to never immediately. A discriminant property is a property with a literal type that tells union members apart.
Two practical consequences follow:
- A function parameter of type
string & numberaccepts no argument, so every call to it fails to compile. - If a type you built through intersections turns into
never, look for properties that have conflicting literal types.
Conflicts between non-literal property types do not always collapse the whole type. { id: string } & { id: number } stays an object type, but its id property has type never.
never in unions
Because never is the empty set, adding it to a union changes nothing, much like adding zero to a number.
type B = string | never; // stringThis property makes never useful as a filter. A conditional type can return never for the members you want to drop, and they vanish from the resulting union:
type Without<T, U> = T extends U ? never : T;
type A = Without<"a" | "b" | "c", "a">; // "b" | "c"A later chapter in this tutorial covers conditional types in detail. For now, remember that never in a union position means "nothing here".
The empty array that infers never[]
One place where never appears without you asking for it is an empty array literal with no contextual type, when strictNullChecks is on:
const config = { items: [] };
// config.items.push(1);
// error: Argument of type 'number' is not assignable to parameter of type 'never'.
const typed: { items: number[] } = { items: [] };
typed.items.push(1); // OKThe compiler cannot guess the element type from [], so it picks the empty set. Nothing can be added to a never[]. The fix is to annotate the variable or the property. Plain const items = []; behaves differently, since the compiler tracks the array's type as you push into it, so annotate when the array is a property or is returned from a function.
Edge cases and pitfalls
- Unreachable code is not always an error. After a call to a
neverfunction, the compiler marks the following statements as unreachable. Whether that produces an error depends onallowUnreachableCode. When the option is unset, editors show the code greyed out, buttscreports no error. - Do not use never as "any other type". A parameter typed
neveraccepts nothing. If you want "any value, but I will check it first", useunknown. - A
neverresult hides bugs. If a generic helper silently returnsnever, the result is assignable to everything, so the compiler will not complain when you use it. Check hover types on results of heavy conditional types. - Promises. An
asyncfunction that always throws has type() => Promise<never>, not() => never. Control-flow narrowing does not treat a call to it as a dead end, because the caller still gets a promise back. - Property access.
keyof {}isnever, because an empty object type has no known keys. A mapped type overneverproducesnever.
Summary of the working model
| Situation | Resulting type | Column |
|---|---|---|
| Function that always throws, with an explicit annotation | `never` | |
| Narrowing that eliminates every union member | `never` | |
| `string & number` | `never` | |
| `T \ | never` | `T` |
| `[]` in an object literal with no context | `never[]` |
Exercise
The function below has no return type annotation. Its return type is inferred as void, so the line after the call in getName is not treated as unreachable. What one change makes getName compile with name narrowed to string, and why does void not work here?
function stop(reason: string) {
throw new Error(reason);
}
function getName(name: string | undefined): string {
if (name === undefined) {
stop("name is required");
}
return name;
}
Show answer
Add an explicit return type: function stop(reason: string): never. A function declaration that only throws is inferred as void, which means the compiler assumes the call can return. Control flow then continues after the if, so name is still string | undefined at return name and the compiler reports an error. With : never, the call is a dead end, so the compiler knows execution cannot continue past it inside the if block, and name is narrowed to string afterwards.
Exercise
What is the type of T in each of these lines: type T1 = number | never;, type T2 = { kind: "x" } & { kind: "y" };, and type T3 = Without<"a" | "b", "a" | "b">; (using Without from this chapter)?
Show answer
T1 is number, because never adds nothing to a union. T2 is never, because the discriminant kind cannot be both "x" and "y", so the intersection reduces to the empty set. T3 is never, because the conditional type returns never for both members, and a union of nothing is never.