Higher-order functions
Concept and syntax
A higher-order function accepts or returns a function. Its type describes both the outer call and the inner callback. Function types use (n: number) => number; parentheses and parameter names make the callback contract clear. A closure may capture an outer parameter.
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 makeScale(factor:number):(n:number)=>number{return n=>n*factor;}function apply(n:number,fn:(n:number)=>number){return fn(n);}console.log(apply(4,makeScale(3)),apply(0,makeScale(2)));Expected output:
12 0Common mistake
Intentionally invalid; compile separately and do not execute.
function apply(n:number,fn:(n:number)=>number){return fn(n);}apply(4,n=>String(n));Expected diagnostic: TS2322. The callback must return a number, not text. Return a numeric result.
Practice and recap
Create makeOffset and pass it to apply.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Higher-order functions — 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 makeScale(factor:number):(n:number)=>number{return n=>n*factor;}function apply(n:number,fn:(n:number)=>number){return fn(n);}console.log(apply(4,makeScale(3)),apply(0,makeScale(2)));Which diagnostic and explanation match the rejected example under the lesson settings?
function apply(n:number,fn:(n:number)=>number){return fn(n);}apply(4,n=>String(n));