Contextual typing
Concept and syntax
Contextual typing flows from an expected type into an expression. A callback is a function passed to another function; when its expected signature is (n: number) => number, the parameter can be inferred as number. The arrow n => n * 2 is a short function expression. The surrounding signature gives n a type, unlike an isolated untyped parameter under strict mode.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
function apply(n: number, transform: (n: number) => number): number { return transform(n);}console.log(apply(4, n => n * 2), apply(4, n => n + 1));Expected output (one line per log):
8 5Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
function apply(n: number, transform: (n: number) => number) { return transform(n); }apply(4, n => n.toUpperCase());Expected compiler diagnostic: TS2339. The callback parameter is inferred as number, which has no toUpperCase method. Use numeric operations.
Practice and recap
Pass a callback that subtracts 1 to apply. Then try a callback returning a string and identify the incompatible result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Contextual typing — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Where does the callback parameter type come from here?
What is the benefit of contextual typing?
Why is toUpperCase invalid inside the callback?
function apply(n: number, transform: (n: number) => number) { return transform(n); }apply(4, n => n.toUpperCase());