Basic · 7 of 13 · 13 min read
Unions and intersections
Why a union gives you a smaller surface and an intersection a larger one, and why that is the opposite of what "or" and "and" suggest.
- Unions and intersections
A union A | B is a value that is one of them. An intersection A & B is a value that is both at
once. The part that catches people is what you can do with each — because the members go the
opposite way to the values.
Unions
type ID = string | number;
let id: ID = 123;
id = "abc"; // both are fine
// id = true; // 'boolean' is not assignable to 'ID'
The usable surface is only what every member shares:
function format(value: string | number) {
// return value.toUpperCase(); // not on number
// return value.toFixed(2); // not on string
return value.toString(); // on both
}
console.log(format("ab"), format(1.5)); // "ab" "1.5"
Which is not a limitation so much as the point: the compiler will not let you call something that only works half the time. Narrowing is how you get the rest.
function format(value: string | number) {
if (typeof value === "string") return value.toUpperCase(); // value: string
return value.toFixed(2); // value: number
}
console.log(format("ab"), format(1.5)); // "AB" "1.50"
Unions of object types
Same rule, applied to properties:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
function area(shape: Circle | Square) {
console.log(shape.kind); // fine — on both
// console.log(shape.radius); // Property 'radius' does not exist on 'Square'
if (shape.kind === "circle") return Math.PI * shape.radius ** 2;
return shape.side ** 2;
}
console.log(area({ kind: "square", side: 3 })); // 9
The shared property is what makes narrowing possible, which is why a union of object shapes almost always wants a discriminant — one property with a distinct literal type per member.
Intersections
type Named = { name: string };
type Aged = { age: number };
const both: Named & Aged = { name: "Ana", age: 30 };
// const missing: Named & Aged = { name: "Ana" }; // 'age' is missing
const either: Named | Aged = { name: "Ana" }; // one is enough
console.log(both.name, both.age, either);
An intersection of primitives is usually never, because no value is two primitives at once:
type Impossible = string & number; // never
// const x: Impossible = "a"; // not assignable
And an intersection with a conflicting property makes that property never, which is why the
error surfaces at the use rather than the declaration:
type A = { id: number };
type B = { id: string };
type Conflict = A & B; // id: never
declare const c: Conflict;
console.log(typeof c.id);
// const bad: Conflict = { id: 1 }; // not assignable
// const also: Conflict = { id: "1" }; // not assignable either
A | B |
A & B |
|
|---|---|---|
| The value is | one of them | both at once |
| Usable members | only the shared ones | all of them |
| Adding a member type | narrows what you can do | widens it |
| Assignable from | either | only something satisfying both |
| Conflicting property | fine — narrow to resolve | becomes never |
The second row is the one worth saying out loud in an interview: union of types, intersection of members.
Where each belongs
Unions model a value that varies:
type Status = "idle" | "loading" | "done";
type Maybe<T> = T | null;
type Input = string | number | Date;
type Result<T> =
| { ok: true; value: T }
| { ok: false; error: Error };
Intersections model a value that combines:
type WithId = { id: number };
type WithTimestamps = { createdAt: Date; updatedAt: Date };
type Entity = WithId & WithTimestamps;
type Props = { title: string } & React.HTMLAttributes<HTMLDivElement>;
const entity: Entity = { id: 1, createdAt: new Date(0), updatedAt: new Date(0) };
console.log(entity.id);
The mixin-style A & B & C is the common real use: small reusable fragments combined into a
concrete shape.
Distribution over unions
A union distributes through the places you would hope:
type Status = "on" | "off";
type Handler = (status: Status) => void; // takes either
type Pair = [Status, Status]; // four combinations of values
type Keyed = Record<Status, number>; // { on: number; off: number }
type Prefixed = `is-${Status}`; // "is-on" | "is-off"
const k: Keyed = { on: 1, off: 0 };
const p: Prefixed = "is-on";
console.log(k.on, p);
Unions also collapse duplicates and absorb wider members, which occasionally surprises:
type A = string | string; // string
type B = string | "literal"; // string — the literal is absorbed
type C = "a" | "b" | "a"; // "a" | "b"
const b: B = "anything"; // because B is just string
console.log(b);
never is the empty union
type Nothing = never;
type Still = string | never; // string — never adds nothing
function fail(message: string): never {
throw new Error(message);
}
never is the union with no members, which is why it disappears from a union and why it is what a
fully narrowed value becomes — the basis of exhaustiveness checking.
type Shape = { kind: "circle" } | { kind: "square" };
function area(shape: Shape): number {
if (shape.kind === "circle") return 1;
if (shape.kind === "square") return 2;
// Here `shape` is `never` — every member has been handled.
return fail(`unhandled: ${JSON.stringify(shape)}`);
}
console.log(area({ kind: "square" })); // 2
Common mistakes
Expecting the union to merge the properties
Mistake. Reading shape.radius off a Circle | Square because one of them has it.
Why it fails. The accessible surface is the intersection of the members’ properties — only
what all of them declare.
What to do instead. Narrow first, usually with a discriminant.
Reaching for an intersection where a union was meant
Mistake. type Status = "on" & "off" for “one or the other”.
Why it fails. That asks for a value that is both strings at once, which is never.
What to do instead. "on" | "off". The & is for combining shapes, not alternatives.
Building a union of object types with no discriminant
Mistake. type Shape = { radius: number } | { side: number }.
Why it fails. Nothing is shared, so nothing can be read and narrowing needs in checks or a
custom guard at every use.
What to do instead. Add a literal kind to each member, and narrow with one comparison.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
A union value is only known to be one of its members, so only what they all share is safe.
Why is .toUpperCase() an error here?
function format(value: string | number) {
return value.toUpperCase();
}A union combines values, but what does an intersection A & B require?
A union of object types gives access only to the properties every branch declares.
Which property can be read without narrowing?
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
function area(shape: Circle | Square) {
// ?
}Why is string | undefined better than making a parameter optional in a public API?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.