Multiple type parameters
Concept and syntax
Use distinct type parameters when a function relates independently chosen types, such as input T and output U. The callback (x:T)=>U links the input to the output. The checker infers each from suitable arguments; reusing one parameter would require a relationship that might not exist.
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 transform<T,U>(x:T,fn:(x:T)=>U):U{return fn(x);}const length:number=transform("tea",x=>x.length);const label:string=transform(7,x=>String(x));console.log(length,label);Expected output:
3 7Common mistake
Intentionally invalid; compile separately and do not execute.
function transform<T,U>(x:T,fn:(x:T)=>U):U{return fn(x);}transform<string,number>("tea",x=>x);Expected diagnostic: TS2322. The explicit U requires number, but the callback returns string. Return x.length.
Practice and recap
Transform a boolean into a descriptive string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Multiple type parameters — 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 transform<T,U>(x:T,fn:(x:T)=>U):U{return fn(x);}const length:number=transform("tea",x=>x.length);const label:string=transform(7,x=>String(x));console.log(length,label);Which diagnostic and explanation match the rejected example under the lesson settings?
function transform<T,U>(x:T,fn:(x:T)=>U):U{return fn(x);}transform<string,number>("tea",x=>x);