capypad
0 day streak
typescript / expert
Snippet

Advanced Inference with Contravariant Parameters

This expert-level snippet demonstrates how to transform a union type into an intersection type. It exploits the fact that function parameters are contravariant, forcing TypeScript to reconcile multiple union members into a single intersection during inference.

snippet.ts
typescript
1
2
3
4
5
6
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends
((k: infer I) => void) ? I : never;
 
type Result = UnionToIntersection<{ a: 1 } | { b: 2 }>;
// Result: { a: 1 } & { b: 2 }
Breakdown
1
(U extends any ? (k: U) => void : never)
Distributes the union into a union of functions.
2
extends ((k: infer I) => void) ? I : never
Infers the parameter type. Since it's in a contravariant position, the union is merged into an intersection.