Functions and Type NarrowingLesson 3.5
Higher-order functions and function types in TypeScript
function type syntax, arrow function types, callbacks, returning functions, type inference with higher-order functions, Function type pitfall
Function types
Functions are values, so they have types too. Two equivalent syntaxes:
// Inline type
const double: (n: number) => number = (n) => n * 2;
// Type alias
type Transformer = (n: number) => number;
const triple: Transformer = (n) => n * 3;Callbacks
function applyAll(nums: number[], fn: (n: number) => number): number[] {
return nums.map(fn);
}
applyAll([1, 2, 3], double); // [2, 4, 6]Returning functions (closures)
function multiplier(factor: number): (n: number) => number {
return (n) => n * factor;
}
const times5 = multiplier(5);
times5(4); // 20Avoid the Function type
The uppercase Function type accepts any function but loses all parameter and return type information. Always use specific function signatures instead. TypeScript infers callback types from context in most higher-order function cases, so you rarely need to annotate explicitly.
