Inference candidate variance
Concept and syntax
Multiple covariant inference candidates can form a union; contravariant candidates can form an intersection when there are no covariant candidates. The repeated infer variable is not a requirement that all candidate types be identical. Use function properties with strict checking to illustrate input positions.
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 Out<T>=T extends {a:infer U;b:infer U}?U:never; type In<T>=T extends {a:(x:infer U)=>void;b:(x:infer U)=>void}?U:never;type Both=In<{a:(x:{id:number})=>void;b:(x:{label:string})=>void}>;const x:Out<{a:string;b:number}>=5; const y:Both={id:1,label:"tea"}; console.log(x,y.label);Expected output:
5 teaCommon mistake
Intentionally invalid; compile separately and do not execute.
type Out<T>=T extends {a:infer U;b:infer U}?U:never; type In<T>=T extends {a:(x:infer U)=>void;b:(x:infer U)=>void}?U:never;type Both=In<{a:(x:{id:number})=>void;b:(x:{label:string})=>void}>;const y:Both={id:1};Expected diagnostic: TS2322. Both contravariant input requirements must be satisfied.
Practice and recap
Compare disjoint primitive input types, then examine never.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inference candidate variance — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Inference candidate variance is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Out<T>=T extends {a:infer U;b:infer U}?U:never; type In<T>=T extends {a:(x:infer U)=>void;b:(x:infer U)=>void}?U:never;type Both=In<{a:(x:{id:number})=>void;b:(x:{label:string})=>void}>;const x:Out<{a:string;b:number}>=5; const y:Both={id:1,label:"tea"}; console.log(x,y.label);Which diagnostic and explanation match the rejected example under the lesson settings?
type Out<T>=T extends {a:infer U;b:infer U}?U:never; type In<T>=T extends {a:(x:infer U)=>void;b:(x:infer U)=>void}?U:never;type Both=In<{a:(x:{id:number})=>void;b:(x:{label:string})=>void}>;const y:Both={id:1};What happens to In when both input candidates are string and number respectively?