Unions and intersections#
A | B is “either”; A & B is “both”.
A union of two primitives.
type ID = string | number;
const id: ID = "abc";
Intersection combines object structures.
type Timestamped = {createdAt: Date};
type User = {id: string; name: string};
type Row = User & Timestamped;
A discriminated union pairs each member with a literal tag the operator switches on; the compiler narrows automatically.
type Shape =
| {kind: "circle"; r: number}
| {kind: "rect"; w: number; h: number}
| {kind: "tri"; a: number; b: number; c: number};
The discriminator drives the narrow.
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "rect": return s.w * s.h;
case "tri": return /* … */ 0;
}
}
References#
Literal types for the literal-tag mechanism behind discriminated unions.
Control flow for
neverexhaustiveness.