Union & Intersection Types: OR and AND

Union & Intersection Types: OR and AND in TypeScript: The morning sort at a delivery office runs against a wooden frame of pigeonholes, and the labels on those…

The Analogy: The Sorting Frame at a Delivery Office

The morning sort at a delivery office runs against a wooden frame of pigeonholes, and the labels on those holes are the whole story. One hole is labelled for the Kirkby van or the Ormskirk van, because a few streets are served by whichever van has room that day. An item can go in that hole if it is bound for either round, which makes the hole generous about what it accepts. What it is not generous about is what the clerk may then assume: standing at that hole he knows only what is true of both rounds, that the item leaves before noon, and nothing more, because he cannot yet tell which van will take it.

A second hole is labelled for the recorded barcode and the signature docket together. Nothing goes in it unless it carries both papers, which makes it fussy about what it accepts. In exchange the clerk may read anything printed on either paper, the barcode number and the name to be signed for, because every item in that hole is guaranteed to have both. The two holes pull in opposite directions, and that opposition is the entire lesson: the "either" hole takes more items but tells you less about each one, while the "both" hole takes fewer items but tells you more.

There is a third label the supervisor chalks up now and then as a warning, a hole marked for the van that is both the early van and the late van. No such van exists, so nothing is ever filed there, yet the label hangs on the frame looking like a valid instruction. A new starter can spend a genuine minute holding an item up to it before working out that no item on earth could belong. The label is well formed and completely empty, and the frame gives no hint of the difference until you try to use it.

The failure mode is the one every relief sorter falls into. Standing at the Kirkby-or-Ormskirk hole, he notices the top dozen items are all Kirkby, and he starts sorting by a rule that only makes sense for Kirkby, the estate-block sub-round that Ormskirk does not have. It works all morning because the run happens to be Kirkby-heavy. Then one Ormskirk item surfaces, has no block number, and the rule has nowhere to put it. He was reading a member that only one arm of the "or" guarantees, and the "or" never promised it.


Syntax or Core Structure

Two operators, two opposite jobs. A union, written with a single bar, names a value that is one of several types: the "or" hole. An intersection, written with an ampersand, names a value that is all of several types at once: the "both" hole. Both build new types out of existing ones without declaring anything new.

// src/frame.ts
type Round = "kirkby" | "ormskirk" | "aughton";   // a union of string literals
type Ref = string | number;                       // a union of primitives

type Item = { ref: Ref; round: Round; grams: number };
type Recorded = { barcode: string };
type SignedFor = { signee: string };
type Tracked = Item & Recorded & SignedFor;       // an intersection of three shapes

const plain: Item = { ref: 5012, round: "kirkby", grams: 240 };
const tracked: Tracked = {
    ref: "RM-88", round: "ormskirk", grams: 500,
    barcode: "JG419055236GB", signee: "A. Whitton"
};

function show(item: Item): string {
    const tag = typeof item.ref === "number" ? "no." + String(item.ref) : item.ref;
    return tag + " " + item.round + " " + String(item.grams);
}

console.log(show(plain));
console.log(show(tracked), tracked.barcode, tracked.signee);
console.log(plain.grams + tracked.grams);

Output:

no.5012 kirkby 240
RM-88 ormskirk 500 JG419055236GB A. Whitton
740

Round is the "or" hole: a value is one of three exact words, and any other string is refused where a Round is wanted. Tracked is the "both" hole: a value is an Item and carries a barcode and carries a signee, all three, which is why the last two console.log arguments can read barcode and signee with nothing objecting. show takes a plain Item, so tracked is accepted there too, because an intersection is assignable to any of its parts.

The one asymmetry worth noticing now is inside show. item.ref is string | number, and the typeof test is not decoration: without it, neither toUpperCase nor toFixed would be reachable, because a union only offers what every arm shares. That restriction is the subject of the next section.


Technical Depth: More Options, Fewer Guarantees

The two operators move a type in opposite directions along one axis. A union widens the set of accepted values and narrows the set of members you may read; an intersection narrows the values and widens the members. Everything else in this section is a consequence of that single trade.

The union restriction

Standing at the "or" hole, you may only use what every arm guarantees. A string | number offers toString, which both primitives have, and refuses toUpperCase and toFixed, which belong to only one arm each.

// src/reach.ts
function stamp(ref: string | number): string {
    // ref.toUpperCase();   // refused: number has no toUpperCase
    // ref.toFixed(2);      // refused: string has no toFixed
    return ref.toString();  // allowed: both arms share toString
}

console.log(stamp("RM-88"), stamp(5012));

Output:

RM-88 5012

Output (tsc, for the first commented line):

error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

The elaboration line names the guilty arm. To reach an arm-specific member you must first narrow, with typeof, instanceof, an in test or a literal discriminant, and only inside the branch where the checker knows which arm you hold does that member become reachable.

The trade, laid out

Read this as one idea seen from both sides. The union column and the intersection column disagree on every row, because they are opposites, not variants.

QuestionThe union, one barThe intersection, ampersand
Which values does it acceptAny value matching either operandOnly a value matching every operand
How large is the set of valuesLarger than either operand aloneSmaller than either operand alone
Which members may you readOnly those every operand sharesEvery member of every operand
What must you do before arm-specific readsNarrow to one arm firstNothing, all members are already present
What happens on a conflicting memberThe member becomes a union of its typesThe member collapses, often to never
Everyday jobStates, variants, ids that varyMixins, adding metadata to a shape

When both collapses to nothing

An intersection of objects merges their members. If two operands disagree on the type of a shared member, the merge keeps the intersection of those two member types, and for two different string literals that intersection is never: a member no value can supply, so the whole type becomes uninhabited while still looking well formed.

// src/collapse.ts
type Early = { shift: "early"; van: number };
type Late = { shift: "late"; van: number };
type BothShifts = Early & Late;    // shift is "early" & "late", which is never

type Pinned = number & 240;        // number & the literal 240 keeps 240
const w: Pinned = 240;             // fine: 240 is a number and is exactly 240
// const bad: Pinned = 500;        // refused: 500 is not the literal 240

console.log(w, typeof w, w * 2);

Output:

240 number 480

Output (tsc, for the commented line):

error TS2322: Type '500' is not assignable to type '240'.

BothShifts is the chalked warning label from the analogy: a type that reads as an instruction but that no value can satisfy, because its shift member is never. Nothing catches it at the point of declaration; you find out only when every object you try to assign is rejected. When that happens, do not add members, look for the one member whose two operands disagree. Pinned shows the benign case, where number and the literal 240 overlap in exactly one value and the intersection keeps it.

What reaches the runtime

Neither operator emits anything. A union is a compile-time statement that a value is one of several types, an intersection that it is all of them, and both are erased before the program runs. There is no operator to ask a value at runtime whether it "is a union"; the JavaScript that ships sees ordinary values and the ordinary typeof, instanceof and property tests you wrote to narrow them. The type told the checker which reads were safe. It left no trace to enforce that on its own.


Real World Example: The Dispatch Sheet at the Delivery Office

The office prices a tray of items and prints one sheet. The model uses both operators for real work: Round is a union of literals, Handling is a discriminated union of three classes, and Item is the intersection of a base shape with that union, which distributes into three fully-formed variants.

// src/dispatch.ts
type Round = "kirkby" | "ormskirk" | "aughton";
type Ref = string | number;

type Base = { ref: Ref; round: Round; grams: number };
type Handling =
    | { kind: "standard" }
    | { kind: "recorded"; barcode: string }
    | { kind: "signed"; barcode: string; signee: string };
type Item = Base & Handling;

const TRAY: readonly Item[] = [
    { ref: 5012, round: "kirkby", grams: 90, kind: "standard" },
    { ref: "RM-88", round: "ormskirk", grams: 500, kind: "signed",
        barcode: "JG419055236GB", signee: "AW" },
    { ref: 5044, round: "kirkby", grams: 250, kind: "recorded", barcode: "RN220" },
    { ref: 6001, round: "aughton", grams: 800, kind: "standard" },
    { ref: "RM-90", round: "ormskirk", grams: 120, kind: "recorded", barcode: "RN221" }
];

const ROUND_ORDER: readonly Round[] = ["kirkby", "ormskirk", "aughton"];
const KIND_ORDER: readonly Handling["kind"][] = ["standard", "recorded", "signed"];

function pad(text: string, width: number): string {
    return text.length >= width ? text : text + " ".repeat(width - text.length);
}

function label(ref: Ref): string {
    return typeof ref === "number" ? "#" + String(ref) : ref;
}

function band(grams: number): number {
    if (grams <= 100) { return 100; }
    if (grams <= 250) { return 150; }
    if (grams <= 500) { return 200; }
    return 250;
}

function surcharge(item: Item): number {
    if (item.kind === "standard") { return 0; }
    if (item.kind === "recorded") { return 45; }
    return 85;                              // item is narrowed to the signed variant
}

function proof(item: Item): string {
    if (item.kind === "standard") { return "none"; }
    if (item.kind === "recorded") { return item.barcode; }
    return item.signee;                     // only the signed variant has a signee
}

function fee(item: Item): number {
    return band(item.grams) + surcharge(item);
}

function sheet(tray: readonly Item[]): string {
    const out: string[] = [];
    const rounds = new Set(tray.map((i) => i.round)).size;
    out.push("items: " + String(tray.length) + " across " + String(rounds) + " rounds");
    out.push(pad("REF", 6) + pad("ROUND", 9) + pad("GRAMS", 6) + pad("KIND", 9)
        + pad("PROOF", 7) + "FEE");
    for (const item of tray) {
        out.push(pad(label(item.ref), 6) + pad(item.round, 9) + pad(String(item.grams), 6)
            + pad(item.kind, 9) + pad(proof(item), 7) + String(fee(item)));
    }
    const totalGrams = tray.reduce((sum, i) => sum + i.grams, 0);
    const totalFee = tray.reduce((sum, i) => sum + fee(i), 0);
    const byRound = ROUND_ORDER
        .map((r) => [r, tray.filter((i) => i.round === r).length] as const)
        .filter(([, n]) => n > 0)
        .map(([r, n]) => r + " x" + String(n));
    const byKind = KIND_ORDER
        .map((k) => [k, tray.filter((i) => i.kind === k).length] as const)
        .filter(([, n]) => n > 0)
        .map(([k, n]) => k + " x" + String(n));
    out.push("total grams: " + String(totalGrams));
    out.push("total fee: " + String(totalFee) + "p");
    out.push("by round: " + byRound.join(", "));
    out.push("by kind: " + byKind.join(", "));
    return out.join("\n");
}

console.log(sheet(TRAY));

Output:

items: 5 across 3 rounds
REF   ROUND    GRAMS KIND     PROOF  FEE
#5012 kirkby   90    standard none   100
RM-88 ormskirk 500   signed   AW     285
#5044 kirkby   250   recorded RN220  195
#6001 aughton  800   standard none   250
RM-90 ormskirk 120   recorded RN221  195
total grams: 1760
total fee: 1025p
by round: kirkby x2, ormskirk x2, aughton x1
by kind: standard x2, recorded x2, signed x1

Read the sheet against the trade. Round being a union of three literals is what lets ROUND_ORDER list every round without inventing one that does not exist, and a misspelled round is caught where it is written. Handling being a discriminated union is what makes surcharge and proof safe: inside if (item.kind === "recorded") the checker knows the item has a barcode, and in the final return of each it knows the item is the signed variant, so item.signee is reachable with nothing to guard. Item being the intersection Base & Handling is what distributes the base fields across all three variants, so every row has a ref, a round and a grams no matter its class. The totals cross-check: five items summing to 1760 grams and 1025 pence, split two-two-one by round and two-two-one by kind.

The program has real defects worth naming. Ref is string | number, and label only prefixes a # to the number arm, so a string ref that happens to read as digits, "5012" rather than 5012, would print bare and sit misaligned beside the hashed ones: the union permits a distinction the formatter does not honour. The FEE column prints a bare pence figure while only the footer carries the p, so a reader skimming the rows can easily take 285 for pounds; the type system has nothing to say about a number that means pence in one place and reads as pounds in another. The fee rule is scattered, with weight bands in band and class loadings in surcharge, so adding a fourth class means editing the Handling union, surcharge, proof and KIND_ORDER in four separate places with no single error if you forget one of the last three. And the intersection cuts one way only: because Item is Base & Handling, there is no way to pass Handling on its own to a function that only cares about the class, since every value of it drags the base fields along.


Common Mistakes

  1. Reading the ampersand as "or": it is the opposite. An intersection describes fewer values than either operand alone, because a value must satisfy every operand at once.
  2. Reading the bar as "and": a union describes more values but fewer guaranteed members. You cannot read an arm-specific member until you narrow to that arm.
  3. Reaching for a type assertion to escape a union: (ref as string).toUpperCase() compiles and then throws at runtime when the value was a number. Narrow with typeof instead.
  4. Overlapping object unions with no discriminant: { a?: string } | { b?: string } accepts the empty object and helps no one; add a shared literal kind field so branches can be told apart.
  5. Expecting an intersection of conflicting literals to be usable: { shift: "early" } & { shift: "late" } has shift: never and no value can satisfy it, however well formed the type looks.
  6. Blaming the object when an intersection rejects everything: the fault is almost always one shared member whose two operand types do not overlap; find that member rather than rewriting the value.
  7. Assuming excess-property checks behave normally inside a union: an object literal is checked against the whole union, and the messages can be confusing; annotate the variable's type explicitly for clearer errors.
  8. Forgetting that a union widens a shared member rather than dropping it: in { v: string } | { v: number }, v is string | number, still readable, not gone.
  9. Treating either operator as present at runtime: both are erased, so there is no way to ask a value whether it "is a union"; you must write the ordinary JavaScript checks yourself.

Best Practices

  • Prefer a discriminated union, a shared literal kind field, over in checks or property sniffing: it survives refactors, reads clearly, and enables an exhaustive switch that the compiler polices.
  • Keep unions small and named: type Round = ... at the top of a file beats a seven-member union inlined into a parameter that nobody can reuse or search for.
  • Narrow before you read: reach an arm-specific member only inside the branch where typeof, instanceof, in or a literal discriminant has proved which arm you hold.
  • Use intersections for cross-cutting additions: WithId, WithTimestamps, WithAudit intersected onto a base shape beats copying the same three fields into every type by hand.
  • When an intersection resolves to never, treat it as a design signal, not a bug to force past: the types are reporting a contradiction you asked for, and the fix is in the design.
  • Add an exhaustiveness guard to every discriminated-union switch: a default branch that assigns the value to a never-typed variable turns a forgotten case into a compile error the day the union grows.
  • Give a shared member one meaning across arms: if v means pence in one arm and pounds in another, no union will save you; brand or rename so the ambiguity cannot arise.
  • Push shared fields outside the union and contradictory fields inside it: Base & (A | B) makes "a value with A's field and B's field" unrepresentable, which is usually exactly the invariant you want.

Practice Exercises

  1. The Narrow: Write format(value: string | number | Date): string handling all three arms with typeof and instanceof and no type assertions, then confirm that removing one branch makes the return type complain.
  2. The Mixin: Declare type WithId = { id: string } and type WithAudit = { createdBy: string }, intersect both onto a Ticket shape, build a valid object, then delete createdBy and read the error.
  3. The Contradiction: Write type Weird = { tag: "a" } & { tag: "b" }, try to build a value of it, and explain in one sentence why every object you try is rejected.
  4. The Fourth Class: Add a { kind: "express"; slot: string } arm to the dispatch.ts Handling union, give it a surcharge and a proof, add one express item to TRAY, hand-trace its row and the new by kind line, and verify.