Sub topic 2
Callbacks and Contextual Typing
Assume you know JavaScript functions, callbacks, union types, and how to run TypeScript with tsc. This chapter shows how TypeScript types functions passed to other functions, special return types, asynchronous functions, and overloads.
Callbacks and contextual typing
A callback is a function passed as an argument. A function type describes its parameters and return value. When TypeScript already knows the expected callback type, it uses contextual typing to infer the callback’s parameter types.
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);
// n is inferred as numberThe generic type parameter T is inferred as number. Therefore, n is contextually typed as number. Annotate a callback parameter when the context is missing or when an explicit type improves clarity.
Returning `void` and `never`
void means that callers should not use a function’s return value. A callback typed as returning void can still receive a function that returns a value:
const handlers: Array<() => void> = [];
handlers.push(() => 42); // allowed; the value is ignorednever means that a function cannot finish normally. Such a function may always throw or loop forever. TypeScript uses never for unreachable code and exhaustive checks.
Async functions and `Promise`
An async function always returns a Promise, an object representing a value that will be available later. Annotate the resolved value inside Promise.
async function fetchLength(url: string): Promise<number> {
const response = await fetch(url);
const text = await response.text();
return text.length;
}The function returns Promise<number>, not number. Callers use await or .then() to obtain the number.
Overloads
Use overloads when one function supports several related call shapes and each shape deserves a precise result type. Overload signatures appear first. The implementation signature follows and is hidden from callers.
function toArray(value: string): string[];
function toArray(value: number): number[];
function toArray(value: string | number): (string | number)[] {
return [value];
}
const words = toArray("hello"); // string[]
const numbers = toArray(5); // number[]A union is often simpler when all inputs have the same result type. Prefer overloads when the input type determines a different, useful output type.
Exercise
What type does toArray("x") return in the example?
Show answer
It returns string[] because the string overload matches the call.