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;

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.

Further reading

Problem with a question

TypeScript · Senior · question 25

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz