Sub topic 12
void and never
This chapter covers the two types that describe functions with nothing useful to return: void and never. It assumes you can already type function parameters and return values. It also assumes you know unions, basic narrowing with typeof and ===, and that strictNullChecks is on (it is part of strict).
void: no useful return value
void is the return type of a function whose result the caller is not meant to use. A function with no return statement, or a bare return;, has the inferred return type void.
function log(message: string): void {
console.log(message);
}
const result = log("hello"); // result has type voidAnnotating : void is optional here, since inference reaches the same answer. Many teams still write it on exported functions to document intent.
void is not the same as undefined
At runtime a function with no return statement returns undefined. In the type system the two are different. You can assign undefined to a void variable, but you cannot assign a void value to a variable typed undefined.
let a: void = undefined; // ok
let b: undefined = log("x"); // Error: Type 'void' is not assignable to type 'undefined'.TypeScript also stops you from using a void result in a condition, because that is almost always a bug:
// if (log("x")) { } // Error: An expression of type 'void' cannot be tested for truthiness.Function types with a void return accept any return value
This is the rule that surprises people most. A function type whose return type is void does not require the function to return nothing. It means the caller will ignore whatever comes back.
type Handler = (event: string) => void;
const seen: string[] = [];
const onEvent: Handler = (event) => seen.push(event); // push returns number, still allowed
const forEachResult = [1, 2, 3].forEach((n) => n * 2); // callback returns number, allowedThis rule makes everyday code work. Array.prototype.forEach declares its callback as returning void, so you can pass an arrow function that happens to return something, such as seen.push. If the rule were stricter, concise arrow bodies would fail to compile.
The relaxation applies only to function types and contextually typed function expressions. A function declaration with an explicit : void annotation is still checked strictly:
function strict(): void {
// return 1; // Error: Type 'number' is not assignable to type 'void'.
}Async functions
An async function that returns nothing has the type Promise<void>. Write that type when you annotate it.
async function save(name: string): Promise<void> {
await Promise.resolve(name);
}never: a value that cannot exist
never is the empty type. No value has the type never, so a function returning never can never return normally. There are two such cases: it always throws, or it loops forever.
function fail(message: string): never {
throw new Error(message);
}Two assignability rules define never:
neveris assignable to every type, because there is no value that could break the rule.- No type is assignable to
never, exceptneveritself.
Inference differs between declarations and expressions
TypeScript infers never only for function expressions and arrow functions whose end point is unreachable. A function declaration with the same body is inferred as void.
function a() {
throw new Error("x");
} // () => void
const b = function () {
throw new Error("x");
}; // () => never
const c = () => {
throw new Error("x");
}; // () => neverSo if you write a helper like fail as a function declaration, annotate : never yourself.
never and control flow
When a call targets a function with an explicit never return type, the compiler treats the code after that call as unreachable. This lets a failure helper narrow types just like a throw statement.
function fail(message: string): never {
throw new Error(message);
}
function getName(user: { name?: string }): string {
const name = user.name; // string | undefined
if (name === undefined) {
fail("name is missing");
}
return name; // narrowed to string
}This works only when the called function's name has an explicit type annotation. A declaration such as function fail(...): never qualifies. A const fail = (m: string) => { throw ... } with no annotation does not, because the compiler needs the declared type before it analyzes the caller.
never in exhaustiveness checks
After you handle every member of a union, the leftover type is never. You can pass that leftover to a parameter typed never. If a member is still unhandled, the call fails to compile.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
default:
return assertNever(shape);
}
}Now add | { kind: "triangle"; base: number; height: number } to Shape. The default branch now receives a triangle, and the call assertNever(shape) reports that the triangle type is not assignable to never. The error lands in area, which is the function that needs a new case.
The helper has two jobs. The never parameter gives you the compile-time check. The throw gives you a runtime guard for data that bypassed the type system, such as JSON from a network call that was cast to Shape.
never inside types
never also appears in the type system without any function involved.
- A union drops it:
string | neveris juststring. Conditional types use this to filter union members out. - An intersection of incompatible types reduces to it:
string & numberisnever. - An intersection of object types whose discriminant properties conflict also reduces to
never. For example,{ kind: "a" } & { kind: "b" }isnever.
type Maybe = string | never; // string
type Impossible = string & number; // neverIf a type you expected to be useful shows up as never in an editor hover, look for an intersection like this or a narrowing that removed every member.
Comparing the empty-ish types
| Type | Meaning | Values it holds | Typical use |
|---|---|---|---|
| `void` | Caller should ignore the result | `undefined` | Functions that do work and return nothing |
| `undefined` | The value is exactly undefined | `undefined` | Optional values, missing properties |
| `never` | No value is possible | none | Throwing helpers, exhaustiveness checks |
| `unknown` | Any value, not yet checked | all values | Input of uncertain shape |
never and unknown are opposites. unknown is the top type, and every type is assignable to it. never is the bottom type, and it is assignable to every type.
Common mistakes
- Annotating a callback parameter as returning
neverwhen it merely returnsvoid. A function that returns normally is not assignable to anever-returning type. - Writing
failas an unannotatedconstarrow function and expecting narrowing after the call. Use a function declaration with: never. - Using
anywhereneverfits. A parameter typedneverstops new, unhandled cases from compiling, whileanyaccepts them silently. - Returning a value from a function declared
: voidand being surprised by the error. The relaxed rule applies to function types, not to declarations.
Exercise
What type does TypeScript infer for const stop = () => { throw new Error("stop"); };, and what type does it infer for function stop2() { throw new Error("stop"); }? Which one can you rely on for narrowing after a call, and what must you change in the other?
Show answer
stop is inferred as () => never and stop2 as () => void. Neither is dependable for narrowing as written. Narrowing after a call needs an explicit type annotation on the called function, and stop has none, because its type is only inferred. Declare function stop2(): never { ... } with an explicit return type (the annotated function declaration form works). For stop, add an explicit type such as const stop: () => never = () => { throw new Error("stop"); };.
Exercise
Given type Light = "red" | "yellow" | "green"; and a switch over a Light with cases for "red" and "yellow" only, what does a default branch calling assertNever(light) report, and what type does light have inside that branch?
Show answer
Inside the default branch, light has the type "green". The call assertNever(light) reports that "green" is not assignable to type never. Adding case "green": makes light become never in default, and the error disappears.