Strict function types
Concept and syntax
With strictFunctionTypes enabled, function-valued properties cannot be assigned a callback that accepts only a narrower input than the target promises. This contravariant check prevents callers from supplying inputs the callback cannot handle. Method signatures have a separate compatibility exception.
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 handler:(x:Base)=>number=x=>x.id;const specific:(x:Full)=>number=handler;console.log(specific({id:4,label:"tea"}));Expected output:
4Common mistake
Intentionally invalid; compile separately and do not execute.
type Base={id:number};type Full={id:number;label:string};const handler=(x:Full)=>x.label.length;const general:(x:Base)=>number=handler;Expected diagnostic: TS2322. The target permits a Base without label. Accept Base in the source and narrow if needed.
Practice and recap
Reverse the assignment direction and explain why only one is safe.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strict function types — 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 handler:(x:Base)=>number=x=>x.id;const specific:(x:Full)=>number=handler;console.log(specific({id:4,label:"tea"}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Base={id:number};type Full={id:number;label:string};const handler=(x:Full)=>x.label.length;const general:(x:Base)=>number=handler;