Union to Intersection Conversion
February 9, 20261 min readpart 10/20
Difficulty: Advanced. Prerequisites: Distributive conditional types, function contravariance, infer keyword.
Converting a union type to an intersection type exploits function parameter contravariance to "flip" a union into an intersection. This pattern is essential for merging object types from unions and building complex type utilities.
Key concepts
- Exploiting contravariance in function parameters
- Why (A⇒void)|(B⇒void) becomes (A&B)⇒void in parameter position
- Distribute first, then collect via contravariance
- LastInUnion and UnionToTuple patterns
Example
// The classic trick
type UnionToIntersection<U> =
(U extends any ? (x: U) => void : never) extends (x: infer I) => void ? I : never;
type U = { a: 1 } | { b: 2 };
type I = UnionToIntersection<U>; // { a: 1 } & { b: 2 }
// LastInUnion
type Last<U> = UnionToIntersection<
U extends any ? (x: U) => void : never
> extends (x: infer L) => void ? L : never;
type L = Last<'a' | 'b' | 'c'>; // 'c'
// UnionToTuple
type UTT<U, L = Last<U>> = [U] extends [never] ? [] : [...UTT<Exclude<U, L>>, L];
type T = UTT<'a' | 'b'>; // ['a', 'b']
// Merge union of objects
type Merge<U> = { [K in keyof UnionToIntersection<U>]: UnionToIntersection<U>[K] };
type M = Merge<{ a: 1 } | { b: 2 }>; // { a: 1; b: 2 }
// Used in: type-fest, ts-toolbelt, and middleware/plugin type mergingResources
- Type Challenges - Union to Intersection: The canonical challenge
- Stack Overflow Explanation: Original detailed breakdown
Practice
- Union to Intersection (TypeHero, Hard)
- Union to Intersection (Type Challenges, Hard)
- Union to Tuple (Type Challenges, Hard)
- Tuple to Union (Type Challenges, Medium)
- Merge (Type Challenges, Medium)
Hints
- The key insight is that function parameters are in contravariant position, which flips unions to intersections.
- Use distributive conditional types first to spread the union, then collect with infer in a function parameter.