Function Types and Callbacks
A function type describes the parameter list and return type, for example (value: string) => number. It can be assigned to variables, passed as callbacks, and used in object contracts. Under strict function checking, parameter compatibility matters: a callback should not require arguments the caller might not provide.
When defining event handlers, predicates, sorting callbacks, or plugin APIs, type the callback's inputs based on what the caller promises to pass. A callback's return type should describe what the caller actually uses, such as void for side-effect callbacks.
A reusable callback contract
type Formatter = (value: number) => string;
const currencyFormatter: Formatter = (value) =>
`₹${value.toFixed(2)}`;
function renderValues(values: number[], format: Formatter): string[] {
return values.map(format);
}💡
Formatter can be reused anywhere a number-to-string function is required. The map callback receives each number and returns a string.Key Takeaways
- Function types make callback contracts reusable.
- Match callback parameters to the caller's guaranteed arguments.
voidis appropriate when the caller ignores the callback result.
Knowledge Check
What does `(value: number) => string` describe?