Sub topic 13
Contextual Typing for Callbacks
This chapter assumes you can read function types such as (a: number) => string, you know how inference works for variables, and you have used map, filter, or forEach. It covers how TypeScript types a function expression from the place where you wrote it, and what breaks when you move that function elsewhere.
Types that flow from the surrounding code
Look at this call.
const names = ["Ada", "Grace", "Linus"];
const lengths = names.map((name) => name.length);
// name: string, lengths: number[]The arrow function has no annotation, yet name is a string. TypeScript did not infer that from the function body. It took it from the place where the function appears. names is a string[], and map declares that its callback receives an element of the array. This is contextual typing: an expression gets a type from the type that its position expects.
Ordinary inference works from the value to the type. Contextual typing works from the position to the value. In const n = 5 the value decides the type. In names.map(...) the map signature decides the type of the callback's parameters.
When there is no context
Remove the context and the parameter has nothing to inherit from.
function double(n) {
return n * 2;
}
// Error with noImplicitAny (part of strict): Parameter 'n' implicitly has an 'any' type.A function declaration is not placed anywhere that expects a type, so every parameter needs an annotation. Contextual typing only helps function expressions and arrow functions that appear in a typed position.
Where context comes from
The expected type can come from several places.
| Position | Example | Source of the context |
|---|---|---|
| Argument to a call | `names.map((n) => ...)` | The parameter type in the callee's signature |
| Variable with an annotation | `const f: Formatter = (v, d) => ...` | The annotation |
| Property of a typed object literal | `{ onClick: (e) => ... }` | The property type of the target |
| Return statement | `return (x) => x + 1` | The declared return type of the enclosing function |
| Array element | `const fs: Op[] = [(a) => a]` | The element type |
Here is the annotated variable case.
type Formatter = (value: number, digits: number) => string;
const format: Formatter = (value, digits) => value.toFixed(digits);
console.log(format(3.14159, 2)); // "3.14"Both value and digits come from Formatter. You can write fewer parameters than the type declares, because JavaScript callers may ignore extra arguments.
type Formatter = (value: number, digits: number) => string;
const short: Formatter = (value) => String(value);
console.log(short(7, 2)); // "7"You cannot write more parameters than the type declares.
The same mechanism works for object properties.
type Point = { x: number; y: number };
type Button = {
label: string;
onClick: (position: Point) => void;
};
const button: Button = {
label: "OK",
onClick: (position) => console.log(position.x, position.y),
};
button.onClick({ x: 10, y: 20 });The checking flow
The compiler follows the same steps each time it meets an unannotated function expression.
The return type is checked against the context
Context also applies to the result. If the expected type says a function returns string, the body must produce one.
const label: (n: number) => string = (n) => n * 2;
// Error: Type 'number' is not assignable to type 'string'.There is one exception. When the expected return type is void, the callback may return anything, and the value is ignored.
const out: number[] = [];
[1, 2, 3].forEach((n) => out.push(n)); // push returns number, still allowed
console.log(out); // [1, 2, 3]forEach declares its callback as returning void, so TypeScript accepts the arrow function even though it returns a number. This rule lets you use short arrow bodies without wrapping them in braces.
Losing the context by extracting the callback
The most common error comes from pulling an inline callback into its own declaration.
const words = ["tree", "ox", "river"];
const isLong = (s) => s.length > 3;
// Error: Parameter 's' implicitly has an 'any' type.
console.log(words.filter(isLong));When isLong was written inline inside filter, s was a string. Declared separately, it sits on a line with no expected type, so the context disappears. The fix is to annotate it.
const words = ["tree", "ox", "river"];
const isLong = (s: string) => s.length > 3;
console.log(words.filter(isLong)); // ["tree", "river"]The annotation can also come from a named function type, as with Formatter above. Choose whichever fits: inline callbacks need nothing, and extracted ones need one annotation.
Context keeps literal types
Contextual typing also affects literals. When the expected type is a union of string literals, a literal in that position keeps its narrow type instead of widening to string.
type Mode = "dev" | "prod";
function start(mode: Mode) {
console.log(`starting in ${mode}`);
}
start("dev"); // the literal is checked against Mode directly
const settings = { mode: "dev" };
// start(settings.mode);
// Error: Argument of type 'string' is not assignable to parameter of type 'Mode'.
const typed: { mode: Mode } = { mode: "dev" };
start(typed.mode); // finesettings has no context, so its mode property widens to string. Writing the annotation on typed supplies the context, and "dev" stays a Mode. You can also fix the first case with as const or satisfies, which later chapters cover.
Callbacks in generic functions
Context also flows through generics, and in a particular order. TypeScript first infers type parameters from the arguments that do not depend on context, then types the callback parameters, and only then infers from what the callback returns.
function mapAll<T, U>(items: T[], fn: (item: T) => U): U[] {
return items.map(fn);
}
const result = mapAll([1, 2, 3], (n) => n.toString());
// T is number (from the array), so n: number
// U is string (from the callback's return), so result: string[]
console.log(result); // ["1", "2", "3"]The array argument fixes T as number. That gives n its type. The callback's return value then fixes U as string. If you swapped the arguments so the callback came first, the order would still hold: arguments with no unannotated parameters are inspected first.
This is why adding a type annotation to a callback parameter can change what gets inferred. An annotation makes the function no longer depend on context, so the compiler may use it earlier in inference.
Common errors
- Implicit any after extraction. Move a callback out of its call and add parameter annotations.
- A widened object property. An object literal with no annotation gets general types such as
string. Annotate it, or useas const. - Too many parameters. A callback with more parameters than the expected type declares is an error. Fewer is fine.
- Trusting
anyfrom missing context. WithnoImplicitAnyoff, the unannotated parameter silently becomesanyand the safety is gone. Keep the flag on.
Exercises
Exercise
This code fails to compile under strict mode. Explain why, then fix it. const nums = [5, 12, 8]; const isBig = (n) => n > 10; console.log(nums.filter(isBig));
Show answer
The parameter n has no annotation, and isBig is declared on its own line, so no expected function type exists to give n a type. It becomes an implicit any, which strict mode reports. Annotate it: const isBig = (n: number) => n > 10; Alternatively, inline the arrow function in the filter call, where the context gives n the type number.
Exercise
Given type Handler = (id: number) => void and const h: Handler = (id) => id * 2;, does this compile? What is the type of id, and why is the return value allowed?
Show answer
It compiles. The variable annotation gives id the type number through contextual typing. The expected return type is void, and TypeScript allows a function assigned to a void-returning type to return a value, which it ignores.