Function expressions and callbacks
Concept and syntax
A function expression can receive contextual parameter types from its surrounding contract. In a callback passed to a typed array method, the element parameter is inferred from the array. The callback result must meet the operation’s return contract; contextual typing is not a reason to use 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.
const lengths=["tea","x"].map(text=>text.length);const twice:(n:number)=>number=n=>n*2;console.log(lengths.join(","),twice(4));Expected output:
3,1 8Common mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2551. text is inferred as string, not number. Use length or another string operation.
Practice and recap
Map an array of numeric prices to doubled values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Function expressions and callbacks — 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)?
const lengths=["tea","x"].map(text=>text.length);const twice:(n:number)=>number=n=>n*2;console.log(lengths.join(","),twice(4));Which diagnostic and explanation match the rejected example under the lesson settings?
const lengths=["tea","x"].map(text=>text.toFixed(1));