TypeScript · Senior · Question 25 of 75
How does the UnionToIntersection trick work?
type UnionToIntersection<U> =
(U extends any ? (x: U) => void : never) extends (x: infer I) => void
? I : never;- ✓Correct answer: Inferring from a contravariant parameter position combines candidates into an intersection
- 2The compiler just replaces
|with&via a special rule for this name - 3It doesn't work - an intersection can't be derived from a union
Explanation
First the union is distributed into a union of functions (x: A) => void | (x: B) => void. Then, when inferring I from the (contravariant) parameter position, multiple candidates are combined into an intersection: A & B. It's a textbook example of type-level programming.