Generic inference failures
Concept and syntax
Inference gathers candidates from arguments and context but cannot always infer the relationship you intended. A callback parameter with no candidate for T can remain unknown; annotate the callback or supply an explicit type argument. Simplify signatures and infer from concrete inputs instead of turning off checking with any.
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.
function produce<T>(factory:()=>T):T{return factory();}function use<T>(value:T,fn:(x:T)=>string){return fn(value);}console.log(use(produce(()=>7),n=>n.toFixed(1)));Expected output:
7.0Common mistake
Intentionally invalid; compile separately and do not execute.
function register<T>(fn:(x:T)=>string){}register(x=>x.toFixed(1));Expected diagnostic: TS18046. No concrete candidate establishes T, so the callback parameter is unknown. Specify register<number> or redesign to infer from a value.
Practice and recap
Fix register by giving an explicit argument and then redesign it to accept an initial value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generic inference failures — 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)?
function produce<T>(factory:()=>T):T{return factory();}function use<T>(value:T,fn:(x:T)=>string){return fn(value);}console.log(use(produce(()=>7),n=>n.toFixed(1)));Which diagnostic and explanation match the rejected example under the lesson settings?
function register<T>(fn:(x:T)=>string){}register(x=>x.toFixed(1));