Void callbacks
Concept and syntax
A contextual function type () => void allows a callback that returns a value because the caller promises to ignore that result. This differs from explicitly annotating a function implementation with : void, where returning a number is rejected. Do not rely on an ignored result through the void-typed contract.
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 seen:number[]=[];const visit:(n:number)=>void=n=>seen.push(n);[2,4].forEach(visit);console.log(seen.join(","));Expected output:
2,4Common mistake
Intentionally invalid; compile separately and do not execute.
Expected diagnostic: TS2322. An explicit void implementation cannot return a number. Remove the return value or change its annotation.
Practice and recap
Compare a contextually typed callback with an explicitly annotated void function.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Void 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 seen:number[]=[];const visit:(n:number)=>void=n=>seen.push(n);[2,4].forEach(visit);console.log(seen.join(","));Which diagnostic and explanation match the rejected example under the lesson settings?
function visit(n:number):void {return n;}