Method bivariance
Concept and syntax
Method syntax m(x:T):void has a bivariant parameter compatibility exception even under strictFunctionTypes. This can allow a narrower handler where a broader method contract is expected. Function-valued property syntax m: (x:T)=>void does not have that exception. A successful assignment is not evidence of runtime safety.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
type Base={id:number};type Full={id:number;label:string};const narrow:{run(x:Full):void}={run(x){console.log(x.label);}};const wide:{run(x:Base):void}=narrow;const item:Full={id:1,label:"tea"};wide.run(item);Expected output:
teaThe example only calls wide.run with a full object. A Base-only argument would also be permitted by wide’s static contract, but narrow could then read an absent label. Use a function property when you need the stricter parameter check.
Common mistake
Intentionally invalid; compile separately and do not execute.
type Base={id:number};type Full={id:number;label:string};const narrow:{run:(x:Full)=>void}={run:x=>console.log(x.label)};const wide:{run:(x:Base)=>void}=narrow;Expected diagnostic: TS2322. Function properties reject the unsafe direction. Design handlers for the full promised domain.
Practice and recap
Rewrite the method as a function property and compare the diagnostics.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Method bivariance — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Base={id:number};type Full={id:number;label:string};const narrow:{run(x:Full):void}={run(x){console.log(x.label);}};const wide:{run(x:Base):void}=narrow;const item:Full={id:1,label:"tea"};wide.run(item);Which diagnostic and explanation match the rejected example under the lesson settings?
type Base={id:number};type Full={id:number;label:string};const narrow:{run:(x:Full)=>void}={run:x=>console.log(x.label)};const wide:{run:(x:Base)=>void}=narrow;