Union and Intersection Expansion
What you'll learn: How TypeScript decides when to expand unions and intersections during type inference, and when it defers that expansion for performance.
The Expansion Problem
When TypeScript encounters union or intersection types during inference, it faces a decision: should it expand these types immediately (computing all possibilities), or should it defer expansion (keeping the types lazy)?
Think of expansion like unpacking nested boxes. Sometimes you need to see what's inside right away, but other times it's faster to leave the boxes sealed until you actually need the contents.
When TypeScript Expands Unions
TypeScript expands unions eagerly when:
- Checking assignability: Is
A | Bassignable toC? TypeScript must check both branches. - Property access: When you access a property on a union, TypeScript computes which members have that property.
- Control flow narrowing: Narrowing
string | numberwithtypeofrequires expansion to determine what remains.
type Status = "idle" | "loading" | "success" | "error";
// TypeScript expands to check each literal
function handleStatus(s: Status) {
// Expansion happens here to narrow
if (s === "idle") { /* ... */ }
}
When TypeScript Defers Expansion
For performance, TypeScript defers expansion when:
- The union is very large (hundreds of members)
- The type is used in a type parameter that isn't immediately constrained
- Computing the expansion would create exponential complexity
// Large union - TypeScript keeps it lazy
type EventName = "click" | "focus" | "blur" /* ...200 more */;
// Deferred until actually needed
type EventMap<T extends EventName> = { type: T };
Intersection Expansion
Intersections like A & B must be expanded when TypeScript needs to:
- Compute the final object shape (merging properties)
- Check for conflicts between members
- Determine if the intersection resolves to
never
However, deeply nested intersections with generics are often kept lazy until the generic is instantiated.
Why This Matters
Understanding expansion affects performance. Deeply nested conditional types with unions can cause exponential expansion, slowing the compiler. Keeping types simpler or using constraints helps TypeScript defer expansion intelligently.
Key Takeaway: TypeScript balances eager expansion (for correctness) with deferred expansion (for performance), expanding unions and intersections only when necessary for type checking or narrowing operations.