Intersection vs Union for Optional Properties
You'll learn how intersections and unions handle optional properties in surprisingly different ways — and when each is actually useful.
The Core Difference
When you combine types that have optional properties, intersections and unions behave opposite to what you might expect:
- Intersections (
&) make optional properties more required - Unions (
|) make optional properties more optional
Think of it this way: an intersection means "must satisfy both types," while a union means "could be either type." This logic extends to optional properties in counterintuitive ways.
Intersections: Strengthening Requirements
type HasName = { name?: string };
type HasAge = { age?: number };
type Person = HasName & HasAge;
const p: Person = {}; // ✓ Valid - both properties still optional
const p2: Person = { name: "Alice" }; // ✓ Valid
Wait — both are optional? Yes! The intersection means "has the structure of both," not "requires both properties." The ? remains.
But if properties conflict:
type A = { value?: string };
type B = { value?: number };
type C = A & B; // value?: string & number (becomes never!)
Unions: Creating Optionality
type Config1 = { debug: boolean };
type Config2 = { verbose: boolean };
type Config = Config1 | Config2;
const c1: Config = { debug: true }; // ✓ Valid
const c2: Config = { verbose: false }; // ✓ Valid
// But accessing requires narrowing - you can't assume both exist!
With unions, you can only safely access properties that exist in all variants.
Key Takeaway: Intersections combine structures (optional properties stay optional), while unions create alternatives (making property access uncertain). Use intersections to merge capabilities, unions to represent distinct variants.