Sub topic 8
Assigning to and from unions and intersections
This chapter assumes you know the assignability relation (a source type checked against a target type) and structural typing for objects. Here you will see how the checker handles the case where either side is a union (A | B) or an intersection (A & B).
The four rules
A union and an intersection each have two roles: the source (the value) or the target (the place it goes). That gives four cases, and the checker applies a different rule to each.
| Case | Rule | Reading | Column |
|---|---|---|---|
| Source is a union `A \ | B` | Every member must be assignable to the target | A value could be either member, so both must fit |
| Target is a union `A \ | B` | The source must be assignable to at least one member | Any one member that fits is enough |
| Target is an intersection `A & B` | The source must be assignable to every constituent | The value must satisfy both | |
| Source is an intersection `A & B` | At least one constituent must be assignable to the target, or the combined members must fit | The value is both, so it has everything either has |
Source is a union: every member must fit
Think in sets. string | number is the set of all strings plus all numbers. That set fits inside string | number, but it does not fit inside string, because the numbers fall outside.
declare const sn: string | number;
declare const s: string;
const wide: string | number = s; // OK: string is one member of the target
const narrow: string = sn; // Error: Type 'number' is not assignable to type 'string'
declare const maybe: string | undefined;
const name1: string = maybe; // Error under strictNullChecks
const name2: string = maybe ?? "anon"; // OK: the expression is stringThe error message names the failing member. When the source union is large, the compiler reports the first member that fails, so fixing that member may reveal the next one.
Target is a union: one member is enough
For a non-union source, TypeScript tries each target member and accepts the first that works.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
const c: Shape = { kind: "circle", radius: 1 }; // OK
const bad: Shape = { kind: "circle", size: 2 }; // Error: 'size' does not exist in type circleThe second error comes from a more specific check described in the next section.
Excess property checks with unions
A fresh object literal is checked for excess properties. When the target is a union, the rule depends on whether the union has a discriminant, which is a property whose type is a literal in each member.
- With a discriminant, the checker uses the literal's value to pick one member. Properties that do not belong to that member are excess.
- Without a discriminant, a property is excess only if no member declares it.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
const tooMuch: Shape = { kind: "circle", radius: 1, size: 2 }; // Error: 'size' does not exist in the circle member
type AorB = { a: number } | { b: number };
const both: AorB = { a: 1, b: 2 }; // OK: each property is known by some memberThe both line compiles because { a: 1, b: 2 } is assignable to { a: number } and no member is singled out by a discriminant. The union still permits extra properties that only a different member declares.
Discriminant decomposition
A source whose discriminant is itself a union can be assignable to a union target even though no single target member accepts it as a whole. The compiler splits the source into one case per discriminant value and checks each case. It does this only when the number of combinations is small (25 or fewer).
type Flag =
| { on: true; label: string }
| { on: false; label: string };
declare const b: boolean;
const flag: Flag = { on: b, label: "x" }; // OK: boolean is true | false, and each case matches a memberWithout the decomposition, { on: boolean; label: string } would fail against both members. The behavior is what you would expect from sets, since the source set is exactly the union of the two target sets.
Target is an intersection: satisfy every part
An intersection is the set of values that belong to all constituents. A source must therefore be assignable to each one.
interface HasName { name: string }
interface HasAge { age: number }
type Person = HasName & HasAge;
const p: Person = { name: "Ada", age: 36 }; // OK
const onlyName: Person = { name: "Ada" }; // Error: Property 'age' is missing
function greet(h: HasName) {}
greet(p); // OK: Person is assignable to HasNameThe last line shows the source-intersection rule. A Person has everything HasName requires, so one constituent already fits. When the target needs properties from several constituents, the compiler checks the intersection's combined members instead.
type Named = { name: string } & { id: number };
declare const n: Named;
const x: { name: string } = n; // OK: one constituent is enough
const y: { name: string; id: number } = n; // OK: the combined members satisfy the targetEmpty and conflicting intersections
Intersecting types with no values in common gives an empty set. TypeScript reduces some of these to never, and anything is then assignable from it but nothing useful can be assigned to it.
type Impossible = string & number; // never
type Conflict = { kind: "a" } & { kind: "b" }; // never: the discriminants conflict
type Loose = { id: string } & { id: number };
// Not reduced to never, but the property 'id' has type never,
// so no object literal can satisfy it.Mixing unions and intersections
Intersection distributes over union, so the compiler normalizes (A | B) & C into (A & C) | (B & C). Pairs that conflict drop out as never.
type Mixed = (string | number) & (string | boolean);
// Expands to (string & string) | (string & boolean) | (number & string) | (number & boolean)
// which reduces to: string
const m: Mixed = "ok"; // OK
const bad: Mixed = 1; // Error: Type 'number' is not assignable to type 'string'Common errors
- Assigning a wider union to a narrower one, as in
string | numbertostring. Narrow the source first. - Expecting an intersection to behave like a union.
A & Bhas more properties than either part, whileA | Bguarantees only what the members share. - Building an object literal for a union type with a property from the wrong member. A discriminant makes this an error. Without one, the compiler allows it.
- Combining two object types whose property types conflict, which leaves a
neverproperty.
Exercise
Given type U = { x: number } | { y: string };, does const u: U = { x: 1, y: "s" }; compile, and why?
Show answer
Yes. The literal is assignable to { x: number }, one member is enough, and U has no discriminant. Both x and y are declared by some member, so neither is an excess property.
Exercise
What is the type (string | number) & (string | boolean) after reduction, and which value types can be assigned to it?
Show answer
It reduces to string. Distributing gives (string & string) | (string & boolean) | (number & string) | (number & boolean). Only the first term survives, and the others are never. Only strings are assignable.