Sub topic 9
any, unknown, never, and void in assignments
This chapter assumes you know that assignability is a relation between a source type and a target type. It also assumes you can read types as sets of values from earlier chapters. Four special types behave differently from ordinary ones in that relation. Knowing how each one acts as a source and as a target explains many confusing errors.
Top and bottom types
If a type is a set of values, two sets bound all the others. The empty set is at the bottom, and the set of every value is at the top.
unknownis the top type. Every value belongs to it, so every type is assignable to it.neveris the bottom type. It has no values, so it is assignable to every type. Vacuously, any value of typeneverfits anywhere, because no such value can exist.anyis not a set. It is an escape hatch that the checker treats as both top and bottom.voidis the "no useful result" type. It is mostly relevant to function return types.
unknown: accepts everything, gives nothing back
As a target, unknown accepts any source. As a source, it is assignable only to unknown and any. To use the value you must narrow it first.
let u: unknown = 1;
u = "now a string"; // OK: anything can go in
const n1: number = u; // Error: unknown is not assignable to number
function toNumber(input: unknown): number {
if (typeof input === "number") return input;
if (typeof input === "string") return Number(input);
throw new Error("not a number");
}Inside each if branch, narrowing turns input into a more specific type that is assignable to number. unknown is the safe choice for data whose shape you don't control, such as parsed JSON or a catch variable.
any: switches the check off
any is assignable to every type except never, and every type is assignable to any. The compiler stops checking in both directions.
const loose: any = JSON.parse('{"id": 1}');
const id: string = loose.id; // compiles, but id is a number at runtime
loose.missing.call(); // compiles, throws at runtime
const impossible: never = loose; // Error: any is not assignable to neverany spreads. A value read from an any has type any, so one any can disable checking across a whole chain of code. The never exception exists because never marks code that should be unreachable, and any would let you claim otherwise.
never: the empty set
Since never is assignable to everything, a function that never returns can appear wherever a value is expected. Nothing except never is assignable to never. That one-way rule is useful for exhaustiveness checks.
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; side: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.r ** 2;
case "square":
return s.side ** 2;
default: {
const unreachable: never = s; // s has been narrowed to never here
return unreachable;
}
}
}If someone adds { kind: "triangle" } to Shape, then s in the default branch has type { kind: "triangle" }. That is not assignable to never, so the compiler reports an error at exactly the place you need to update.
never also appears inside unions and intersections, where it acts as an identity or a collapse, as the table below shows.
void: a return type, not a value
undefined is assignable to void. Other values are not. In the other direction, void is assignable only to unknown, any, and void. In particular, it is not assignable to undefined.
const v: void = undefined; // OK
const w: void = null; // Error under strictNullChecks
const x: undefined = v; // Error: void is not assignable to undefinedThe return-type exception
When the target is a function type whose return type is void, the source function may return anything. The checker ignores the source's return value.
type Callback = () => void;
const cb: Callback = () => 42; // OK: the return value is ignored
const result = cb(); // type of result is void, though 42 exists at runtime
function explicit(): void {
return 42; // Error: number is not assignable to void
}The exception exists so that you can pass arr.push or n => total += n to forEach without wrapping it. It applies only when the void return type comes from the target function type. A declaration that is itself annotated : void is checked strictly, as explicit shows.
How they combine in unions and intersections
The special types follow the set rules from the earlier unions chapter.
| Expression | Result | Reason | Column |
|---|---|---|---|
| `string \ | never` | `string` | The empty set adds nothing to a union. |
| `string \ | unknown` | `unknown` | The top type absorbs everything. |
| `string \ | any` | `any` | `any` absorbs everything. |
| `string & unknown` | `string` | Intersecting with the full set changes nothing. | |
| `string & never` | `never` | Intersecting with the empty set is empty. | |
| `string & any` | `any` | `any` wins in intersections too. |
Summary of assignability
| Type | As source, assignable to | As target, accepts |
|---|---|---|
| `unknown` | `unknown`, `any` | Every type |
| `any` | Every type except `never` | Every type |
| `never` | Every type | Only `never` |
| `void` | `void`, `unknown`, `any` | `void`, `undefined`, `never`, `any` |
Common errors
- Using
anywhereunknownfits. Both accept every input. Onlyunknownforces callers to narrow before use. - Expecting
anyto satisfynever. It does not. Anevertarget needs aneversource. - Treating
() => voidas "returns nothing". It means the caller ignores the return value. A function typed this way can still return data. - Comparing
voidwithundefined. Avoidresult cannot be assigned to anundefinedvariable, even thoughundefinedcan be assigned tovoid.
Exercise
Which of these lines produce an error under strict, and why?
1. const a: unknown = "x"; const b: string = a;
2. const c: any = 5; const d: never = c;
3. const e: () => void = () => "hi";
4. declare const f: void; const g: undefined = f;
Show answer
Lines 1, 2, and 4 produce errors; line 3 compiles. In 1, unknown is assignable only to unknown and any, so it needs narrowing before it can go into a string. In 2, any is assignable to everything except never. In 3, a function type returning void accepts a source that returns any value. In 4, void is not assignable to undefined, although undefined is assignable to void.
Exercise
A union Event = Click | Key gains a third member Scroll. The handler's default branch contains const _check: never = event;. What happens, and why?
Show answer
The compiler reports an error on that line. In the default branch event is narrowed to Scroll, because no case handles it. Scroll is not assignable to never, since only never is. The error points you to the switch that needs a new case.