Union Collapse with Multiple infer Sites
What you'll learn: How TypeScript combines types when the same infer variable appears more than once in a conditional type pattern.
The Core Idea
When you use the same infer variable in multiple positions within a single conditional type, TypeScript must decide what type to assign to that variable. The behavior depends on whether those positions are contravariant (like function parameters) or covariant (like return types).
The rules:
- Covariant positions (return types, promise contents): TypeScript creates a union of all possible matches
- Contravariant positions (function parameters): TypeScript creates an intersection of all possible matches
Think of it like collecting evidence from multiple witnesses. For return types, you're saying "it could be this or that" (union). For parameters, you're saying "it must satisfy this and that" (intersection).
Covariant Collapse: Multiple Return Types → Union
type GetReturnTypes<T> = T extends (...args: any[]) => infer R | infer R
? R
: never;
// Same infer R appears twice in return position
type MultiReturn<T> = T extends {
method1: () => infer R;
method2: () => infer R;
} ? R : never;
type Result = MultiReturn<{
method1: () => string;
method2: () => number;
}>;
// Result = string | number (union!)
TypeScript sees R could be string from method1 and number from method2, so it creates a union.
Contravariant Collapse: Multiple Parameters → Intersection
type GetParams<T> = T extends {
handler1: (arg: infer P) => void;
handler2: (arg: infer P) => void;
} ? P : never;
type Param = GetParams<{
handler1: (arg: { id: string }) => void;
handler2: (arg: { name: string }) => void;
}>;
// Param = { id: string } & { name: string } (intersection!)
Since function parameters are contravariant, TypeScript creates an intersection — the P must satisfy both shapes.
Why This Matters
This behavior is crucial when extracting types from overloaded functions or objects with multiple methods. Understanding union vs intersection collapse helps you predict what type you'll actually get from complex infer patterns.
Key Takeaway: When the same infer variable appears multiple times in a conditional type, TypeScript creates unions for covariant positions (like returns) and intersections for contravariant positions (like parameters).