Sub topic 13
Contextual Typing for Callbacks
This chapter assumes you know how TypeScript infers variable types, can annotate function parameters, and understand union types. You should also be comfortable with array methods such as map and filter.
What contextual typing does
Many functions take other functions as arguments. When you pass an arrow function as a callback, TypeScript often knows the parameter types before you write them. It reads the type from the place where the function is used. This is called contextual typing.
const scores = [72, 91, 58];
const passed = scores.filter((score) => score >= 60);
// score is inferred as number, because filter expects a
// callback whose first parameter matches the array element type.You did not annotate score, yet hovering over it in your editor shows number. The filter method declares its callback as (value: number, index: number, array: number[]) => unknown, and TypeScript applies that signature to your arrow function.
Where the type comes from
The context can be a method signature, a variable with a declared function type, or an argument position. In each case the compiler matches your parameters to the expected parameter types by position.
type ErrorHandler = (code: number, message: string) => void;
const onError: ErrorHandler = (code, message) => {
console.log(`${code}: ${message}`);
};Both code and message are typed from ErrorHandler. If you write onError with a third parameter, the compiler reports an error because the expected signature has only two.
When context is missing
Contextual typing needs a known target type. A function with no surrounding context gets no parameter types. Under strict settings, including noImplicitAny, that is an error.
// Error: Parameter 'n' implicitly has an 'any' type.
const double = (n) => n * 2;
// Fine: the annotation supplies the type.
const doubleTyped = (n: number) => n * 2;Annotate parameters when a function is not passed directly to a typed slot.
Return types in callbacks
The callback's return type also comes from context in some cases. The map method uses the return value of your callback to build a new array, so its type flows into the result.
const labels = [1, 2, 3].map((n) => `item-${n}`);
// labels has type string[]Diagram: deciding whether to annotate
Common errors
- Assigning a function to a variable without a type, then passing it to a typed method. The parameters stay untyped.
- Annotating a parameter with a type that does not match the expected one. The compiler flags the mismatch, which is usually useful.
- Forgetting that a callback with fewer parameters is still valid, while one with more parameters is an error.
const raw = [1, 2, 3];
raw.forEach((value, index, array) => {
console.log(value, index, array.length);
});
// Valid. Callbacks may omit trailing parameters.Exercise
The following code has no type errors under strict settings. What type does TypeScript give to entry inside the callback, and why?
const pairs: [string, number][] = [["age", 30], ["height", 180]];
pairs.forEach((entry) => console.log(entry[0].toUpperCase()));
Show answer
entry has type [string, number]. The forEach method on pairs expects a callback whose first parameter is the element type of pairs, which is the tuple [string, number]. Contextual typing supplies that type, so entry[0] is known to be a string and toUpperCase is valid.