Union and Intersection Types

A union A | B means a value can be either alternative; code can safely access only members common to all alternatives until it narrows the value. An intersection A & B combines requirements, so a value must satisfy both types. Intersections are useful for composing object capabilities, but conflicting property definitions can produce impossible types.

Choose unions to model mutually exclusive states and intersections to combine compatible contracts. Avoid treating A | B as though it automatically exposes all properties from both types; that would be unsafe because a value might only be one branch.

Union and intersection composition
type HasId = { id: string };
type HasTimestamp = { createdAt: Date };
type StoredRecord = HasId & HasTimestamp;

type Result = { data: string } | { error: string };
💡 StoredRecord requires both id and createdAt. Result is one of two shapes; consumers must check which branch they received before accessing branch-specific properties.
Key Takeaways
  • Union means one of several alternatives.
  • Intersection combines all requirements.
  • Narrow unions before using branch-specific properties.
Knowledge Check

What does `A & B` mean for a value?