Sub topic 5
Callbacks and Contextual Typing
Prerequisites
This chapter assumes that you know JavaScript callbacks and arrow functions, basic TypeScript types, arrays, unions, and how to run the TypeScript compiler. A callback is a function passed to another function so that it can be called later or during an operation.
TypeScript can often determine a callback's parameter types from the place where the callback is used. This process is called contextual typing. The surrounding expression provides the context for the function.
How contextual typing works
Consider map:
const names = ["Ada", "Linus", "Grace"];
const nameLengths = names.map(name => name.length);The map method expects a callback that receives an element from the array. Since names is a string[], TypeScript infers that name is a string. You do not need to write name: string.
The inferred types are visible in an editor when you hover over the parameter. The compiler can therefore check name.length and reject operations that do not belong to strings.
flowchart TD
A["string[] array"] --> B["map callback"]
B --> C["name inferred as string"]
C --> D["name.length is allowed"]The same idea applies when a function parameter has a function type:
type Formatter = (value: number) => string;
function formatValues(values: number[], format: Formatter): string[] {
return values.map(format);
}
const labels = formatValues([10, 20, 30], value => `$${value}`);The type Formatter gives the arrow function its context. TypeScript infers value as number and checks that the callback returns a string.
Contextual typing versus explicit annotations
Contextual typing works only when TypeScript has enough information from the surrounding expression. This callback has a known context:
const doubled = [1, 2, 3].map(value => value * 2);This callback does not:
// const operation = value => value * 2;
// Error: Parameter 'value' implicitly has an 'any' typeThe standalone function has no declared parameter type and no surrounding function type. With noImplicitAny enabled, TypeScript reports an error. Add an annotation or assign the function to a typed variable:
const operation = (value: number): number => value * 2;
const typedOperation: (value: number) => number = value => value * 2;Use contextual typing when the expected type is clear. Add explicit annotations when a function is declared independently, exported as part of an API, or needs documentation that the surrounding context does not provide.
| Situation | Example | Parameter type source |
|---|---|---|
| Array method callback | `items.map(item => item.id)` | The array element type |
| Typed function argument | `run(task => task())` | The parameter's function type |
| Standalone callback | `(value: number) => value * 2` | The explicit annotation |
Callback return types
TypeScript also checks the callback's return type against the expected type:
type Predicate<T> = (value: T) => boolean;
function keep<T>(items: T[], predicate: Predicate<T>): T[] {
return items.filter(predicate);
}
const positive = keep([-2, 0, 4], value => value > 0);
// const invalid = keep([1, 2], value => value);
// Error: number is not assignable to booleanThe generic type T connects the array element type to the callback parameter type. For the second call, value is a number, but the callback must return a boolean.
Exercise
What type does TypeScript infer for word in words.filter(word => word.length > 3), assuming words has type string[]?
Show answer
TypeScript infers word as string, because filter gives its callback the array's element type.