Sub topic 5
Callbacks and Contextual Typing
A callback is a function you pass to another function as an argument. TypeScript can often work out a callback's parameter types without annotations. This chapter explains how that works, when it fails, and how to fix the failures.
What this chapter assumes
You should know how to write callbacks and arrow functions in JavaScript. You should also know how to annotate parameters, write function type expressions like (value: T) => boolean, and read a basic generic signature. The earlier chapters on function types and generics cover these.
Typing a callback parameter
The usual way to accept a callback is to give the parameter a function type. A type alias makes that type reusable and gives it a name.
type Predicate<T> = (value: T) => boolean;
function filterItems<T>(items: T[], keep: Predicate<T>): T[] {
return items.filter(keep);
}
const evens = filterItems([1, 2, 3, 4], n => n % 2 === 0); // number[]The call site writes n => n % 2 === 0 with no annotation on n, and the compiler still knows n is a number. That is contextual typing.
What contextual typing is
Contextual typing means the compiler gives an expression a type based on where the expression appears, not only on what it contains. An arrow function written directly in an argument position has an expected type: the parameter type of the function being called. The compiler copies that expected type's parameter types onto the arrow function's parameters.
Three consequences follow:
- You don't repeat types the compiler already knows, so callbacks stay short.
- The callback's body is checked against the expected return type.
- Editor completions work inside the callback, because
nhas a known type.
The compiler does not guess here. It reads the expected function type and applies it.
How the compiler orders the work
With a generic function, T is unknown until the compiler has looked at the arguments. The compiler handles this by deferring callbacks whose parameters lack annotations. These are called context-sensitive functions. It first checks the other arguments, infers the type parameters from them, and only then types the callback.
This order explains why parameter order in your own signatures matters less than you might expect. Both of these calls work, even though the callback comes first in the second one:
function applyTo<T>(value: T, fn: (input: T) => void): void {
fn(value);
}
function applyToFirst<T>(fn: (input: T) => void, value: T): void {
fn(value);
}
applyTo(5, x => console.log(x.toFixed(1)));
applyToFirst(x => console.log(x.toFixed(1)), 5);In both calls the compiler infers T as number from the plain argument 5, then types x.
Inferring a callback's return type
A callback's return type can feed a second type parameter. This is how Array.prototype.map is typed, and you can write the same shape yourself.
function mapItems<T, U>(items: T[], transform: (item: T) => U): U[] {
return items.map(item => transform(item));
}
const lengths = mapItems(["a", "bb", "ccc"], s => s.length); // number[]
const labels = mapItems([1, 2, 3], n => `#${n}`); // string[]Here T comes from the array, which types s and n. U comes from what the callback returns. The two flows go in opposite directions: T flows into the callback, and U flows out of it.
Contextual typing in object literals
Contextual typing is not limited to arguments. Any place with a known expected type provides context: object properties, array elements, return statements, and variables with annotations.
type Options = {
retries: number;
onDone: (result: string) => void;
};
function run(options: Options): void {
options.onDone("finished");
}
run({
retries: 2,
onDone: result => console.log(result.toUpperCase()), // result is string
});
const handler: Predicate<string> = s => s.length > 3; // s is stringIn the last line the annotation on handler supplies the context. The arrow function needs no annotation of its own.
When there is no context
Contextual typing only works when the function expression sits in a position with an expected type. If you define the function separately and pass it later, it has no context at the point of definition.
const isEven = n => n % 2 === 0;
// error with noImplicitAny: Parameter 'n' implicitly has an 'any' type.
filterItems([1, 2, 3], isEven);The compiler checks the declaration of isEven before it sees the call. At that point nothing says what n is, so it falls back to any, which strict mode rejects. There are two fixes. You can annotate the parameter, or annotate the variable with the callback type.
const isEvenNumber = (n: number) => n % 2 === 0;
const isEvenTyped: Predicate<number> = n => n % 2 === 0;
filterItems([1, 2, 3], isEvenNumber);
filterItems([1, 2, 3], isEvenTyped);Annotating a parameter is the simplest fix when the function stands alone. Annotating the variable is better when you already have a named callback type, because it also checks the return type against the alias.
Callbacks may declare fewer parameters
A function with fewer parameters can stand in for a function type with more. The caller supplies all the arguments, and a callback that ignores some is harmless. This is why forEach(item => ...) works even though forEach also passes an index and the array.
type Visitor<T> = (item: T, index: number) => void;
function each<T>(items: T[], visit: Visitor<T>): void {
for (let i = 0; i < items.length; i++) {
visit(items[i], i);
}
}
each(["a", "b"], item => console.log(item.toUpperCase())); // ok: ignores index
each(["a", "b"], (item, index) => console.log(index, item)); // ok
// each(["a"], (item, index, extra) => {}); // error: callback requires more parameters than the caller providesThe reverse direction fails. A callback that requires more parameters than the caller will pass cannot be called safely, so the compiler rejects it.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Parameter 'x' implicitly has an 'any' type` | The function is defined outside any contextual position | Annotate the parameter, or annotate the variable with a function type |
| `Type 'string' is not assignable to type 'boolean'` on a callback | The callback's return value does not match the expected return type | Change the body, or widen the expected type |
| Callback parameter is typed `unknown` | The type parameter was inferred as `unknown` because no other argument fixed it | Pass a typed argument, or give the type argument explicitly: `fn<number>(...)` |
| `Target signature provides too few arguments` | The callback declares more parameters than the caller passes | Remove the extra parameters, or add them to the callback type |
The first row has a variant. If you annotate only some parameters of a callback, the compiler still uses context for the rest of them. This is rarely useful, and a fully annotated callback is easier to read.
Choosing between annotation and inference
Leave callback parameters unannotated when the callback is written inline at the call site. The context is reliable there, and the code is shorter. Add annotations when the callback is declared separately, when it is exported, or when you want the signature to be readable without checking the callee. Name the callback type with an alias when more than one function accepts it.
Exercise
The following code fails to compile with strict enabled. Explain why the same arrow function would compile if it were written inline in the call to filterItems, and give two different ways to fix the declaration.
const isLong = s => s.length > 3;
filterItems(["tree", "oak"], isLong);
Show answer
Written inline, the arrow function sits in an argument position whose expected type is Predicate<T>. The compiler infers T as string from the array and gives s the type string. Declared as a separate const, the arrow function has no expected type when it is checked, so s is implicitly any, which noImplicitAny (part of strict) reports as an error. Fix 1: annotate the parameter, const isLong = (s: string) => s.length > 3;. Fix 2: annotate the variable with the callback type, const isLong: Predicate<string> = s => s.length > 3;.
Exercise
Given function mapItems<T, U>(items: T[], transform: (item: T) => U): U[], what are T and U in mapItems([1, 2, 3], n => n > 1), and what is the type of the result?
Show answer
T is number, inferred from the array, and that type is given to n. U is boolean, inferred from the callback's return type. The result has type boolean[].