Sub topic 1
Types as sets of values: top and bottom types
TypeScript has three special types, any, unknown, and never. This chapter gives you one model that explains how all three behave: a type is a set of values. The rest of the tutorial builds on it.
Prerequisites
This chapter assumes you have the following:
- Basic TypeScript syntax: type annotations, interfaces, and union types.
- Familiarity with JavaScript
typeof,instanceof, andtry/catch. - A way to run the TypeScript compiler (
tsc) or an editor that shows TypeScript errors.
Examples assume "strict": true in tsconfig.json. Without it, some errors shown here do not appear.
A type is a set of values
Read an annotation such as let x: string as "x may hold any value from the set of all strings". Each type describes a set:
booleanis the set{ true, false }."red"is a set with one member. This is a literal type.string | numberis the union of two sets.string & numberis the intersection of two sets.
The compiler's main job is to check that the value you put in a place belongs to the set that place accepts.
Assignability is the subset relation
A value of type S can be assigned to a variable of type T when every member of S is also a member of T. This means S is a subtype of T.
type Id = string | number;
const label: "red" = "red";
const text: string = label; // OK: "red" is a subset of string
const s: string = "abc";
const id: Id = s; // OK: string is a subset of string | number
// const back: string = id; // error: number is not in stringEvery "red" is a string, so the first assignment is safe. The reverse direction fails because Id contains values that string does not.
Object types can seem backwards at first. A type with more properties describes fewer values, so it is the smaller set.
interface Named {
name: string;
}
interface Person extends Named {
age: number;
}
const p: Person = { name: "Ada", age: 36 };
const n: Named = p; // OK: every Person is also a NamedFunction parameters work in the opposite direction. A function that accepts a larger set can stand in for one that accepts a smaller set. With strictFunctionTypes enabled, this is accepted:
const handler: (x: string) => void = (x: unknown) => {
console.log(x);
};
handler("hello");The handler only needs to cope with strings, and the function you gave it copes with everything.
Top and bottom of the hierarchy
Subset relationships form a hierarchy. Two points have special positions:
- The top type contains every possible value. Every other type is a subset of it.
- The bottom type contains no values. It is a subset of every other type.
In TypeScript, unknown is the top type and never is the bottom type. The third special type, any, does not fit into either position cleanly. We cover it below.
unknown: the set of everything
Any value can be assigned to unknown.
let top: unknown;
top = 42;
top = "text";
top = null;
top = undefined;
top = { id: 1 };
top = () => "hi";The reverse direction is restricted. A variable of type unknown may hold anything, so the compiler cannot assume anything about it. You cannot assign it to a narrower type, call it, or read properties from it until you prove what it is.
let u: unknown = "hello";
// const s: string = u; // error: 'unknown' is not assignable to 'string'
// u.toUpperCase(); // error: 'u' is of type 'unknown'
if (typeof u === "string") {
const s: string = u; // OK: narrowed to string
console.log(s.toUpperCase());
}This is the core of the design. Putting a value into a big set loses information, so it is always allowed. Getting a value out of a big set into a smaller one needs evidence, so the compiler makes you supply a check.
never: the empty set
never has no members, so no value can have that type. Two consequences follow from the subset rule.
First, never is assignable to every type. The empty set is a subset of all sets, and the claim "every member of never is a string" is vacuously true.
function impossible(x: never) {
const s: string = x; // OK
const n: number = x; // OK
const o: { id: number } = x; // OK
return [s, n, o];
}Second, nothing except never is assignable to never.
// const bad: never = 1; // error
// const worse: never = undefined; // error
declare const nothing: never;
const fine: never = nothing; // OKA function whose parameter is never can never be called with a real value. That is why never is useful for marking code paths that should not be reachable. Later chapters build exhaustiveness checks on this idea.
any: both directions, no checks
any is not a normal set. It is assignable to every type, which makes it behave like the bottom type. Every type is also assignable to it, which makes it behave like the top type. It sits at both ends at once, and that is why it switches the checker off.
let anything: any = 42;
const s: string = anything; // compiles, even though it holds a number
anything.foo.bar(); // compiles, fails at runtime with a TypeErrorCompare this with unknown, which only allows the "into" direction:
let safe: unknown = 42;
// const t: string = safe; // error
const t = safe as string; // allowed only because you wrote the assertionThe as string on the last line does not check anything at runtime. It tells the compiler to trust you, and Chapter 6 covers when that is acceptable.
How the set operations behave
Because types are sets, unions and intersections follow set algebra. never and unknown are the identity elements for these operations. The helper Equal below lets the compiler verify each claim. If a claim were false, the assignment of true would fail to compile.
type Equal<A, B> =
(<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
? true
: false;
const t1: Equal<string | never, string> = true; // union with the empty set
const t2: Equal<string & unknown, string> = true; // intersection with everything
const t3: Equal<string | unknown, unknown> = true; // union with everything
const t4: Equal<string & never, never> = true; // intersection with the empty set
const t5: Equal<string & number, never> = true; // disjoint sets
const t6: Equal<string | any, any> = true; // any absorbs everything| Expression | Result | Why | Column |
|---|---|---|---|
| `T \ | never` | `T` | Adding no values changes nothing |
| `T & never` | `never` | Nothing is in both sets | |
| `T \ | unknown` | `unknown` | The universe already contains `T` |
| `T & unknown` | `T` | Only `T` is in both sets | |
| `string & number` | `never` | The sets have no common member | |
| `T \ | any` | `any` | `any` absorbs the other member |
Edge cases around the top and bottom
Several other types sit close to the top of the hierarchy. Knowing where they fall prevents confusion.
nullandundefined: withstrictNullCheckson, these are separate single-value types. They are not members ofstring,object, or{}. WithoutstrictNullChecks, they leak into every type, which weakens the whole model.{}: the set of all values exceptnullandundefined. It includes strings and numbers. Since TypeScript 4.8,unknownbehaves like{} | null | undefined.object: all non-primitive values such as objects, arrays, and functions. It excludesstring,number,boolean,bigint,symbol,null, andundefined.void: used for return types of functions whose result is ignored. A function typed to returnvoidmay still return a value when assigned through a function type. Do not treatvoidas a top or bottom type.- Empty literal arrays: with strict checking,
const xs: never[] = []is an array that can hold nothing. Pushing a number into it is an error. This is a common cause of "Argument of type 'number' is not assignable to parameter of type 'never'".
const items: never[] = [];
// items.push(1); // error: 'number' is not assignable to 'never'
const ok: number[] = [];
ok.push(1); // OKIf you see an error that mentions never as the target, a type was inferred as the empty set. Add an explicit annotation to fix it.
Putting the model to use
You can use this model to predict compiler behaviour without memorising rules:
- Ask what set each side describes.
- If the source set is inside the target set, the assignment compiles.
- If not, you need a runtime check (narrowing) or an assertion.
This explains why unknown forces checks, why never fits impossible branches, and why any is dangerous: it is the only type that suspends the subset question.
Exercise
Without running the compiler, say whether each line compiles under strict mode, and why.
1. const a: unknown = [1, 2, 3];
2. declare const u: unknown; const b: string = u;
3. declare const n: never; const c: number = n;
4. const d: never = 0;
Show answer
Line 1 compiles, because every value belongs to the set unknown. Line 2 fails, because unknown is larger than string and the compiler needs a check or an assertion. Line 3 compiles, because the empty set is a subset of every type, including number. Line 4 fails, because only never is assignable to never.
Exercise
What are the types string | never, string & never, and string | unknown, and what rule explains each?
Show answer
string | never is string, because never adds no values to a union. string & never is never, because no value is in both sets. string | unknown is unknown, because unknown already contains every value, including all strings.
Exercise
Why does const xs: never[] = []; xs.push(1); fail, and how do you fix it?
Show answer
never[] is an array whose elements must come from the empty set, so no value, including 1, can be added. Change the annotation to number[], or let the context infer a useful element type.