Union-to-intersection pattern
Concept and syntax
A common union-to-intersection encoding distributes each member into a function parameter, then infers a shared parameter type from the resulting union of signatures. Contravariant candidates yield an intersection in this pattern. It is not an inverse of intersection-to-union and edge cases such as never or any need explicit tests.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type U2I<U>=(U extends unknown?(x:U)=>void:never) extends (x:infer I)=>void?I:never; type Both=U2I<{id:number}|{label:string}>;const b:Both={id:1,label:"tea"}; console.log(b.id,b.label);Expected output:
1 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
type U2I<U>=(U extends unknown?(x:U)=>void:never) extends (x:infer I)=>void?I:never; type Both=U2I<{id:number}|{label:string}>;const b:Both={id:1};Expected diagnostic: TS2322. The inferred intersection requires both object contracts.
Practice and recap
Test disjoint primitive types and compare the result with never.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Union-to-intersection pattern — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Union-to-intersection pattern is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type U2I<U>=(U extends unknown?(x:U)=>void:never) extends (x:infer I)=>void?I:never; type Both=U2I<{id:number}|{label:string}>;const b:Both={id:1,label:"tea"}; console.log(b.id,b.label);Which diagnostic and explanation match the rejected example under the lesson settings?
type U2I<U>=(U extends unknown?(x:U)=>void:never) extends (x:infer I)=>void?I:never; type Both=U2I<{id:number}|{label:string}>;const b:Both={id:1};Why does U2I<{id:number} | {label:string}> require both fields?