Functions in TypeScript
Typing Callbacks & Higher-Order Functions
Master annotating callback functions, higher-order functions (HOFs), generic callback signatures, and handling optional callback parameters in TypeScript.
A Higher-Order Function (HOF) is a function that accepts one or more functions as arguments (callbacks) or returns a function as its result.
TypeScript allows you to write strongly-typed callbacks and higher-order functions using Function Type Expressions or Generics.
1. Typing Callback Parameters
To type a function that accepts a callback, declare the callback parameter with a function type signature (arg1: Type1, ...) => ReturnType.
2. Typing Functions Returning Functions
When a Higher-Order Function returns a new function, specify the return type signature explicitly:
3. Generic Higher-Order Functions
To create reusable Higher-Order Functions (like map, filter, memoize, or pipe), use TypeScript Generics:
4. Handling Optional Parameters in Callbacks
Rule for Callbacks: When writing callback type definitions, do NOT mark callback parameters as optional (?) unless the callback function itself is expected to be called without those parameters.5. Interactive Code Playground
Test higher-order function typing below:
6. Common Pitfalls & Edge Cases
() => void means the caller will ignore any returned value, NOT that the callback is forbidden from returning a value.7. Summary Table
| Pattern | Type Definition Syntax |
|---|---|
| Callback Argument | (arg: T) => R |
| HOF Returning Function | (x: A) => (y: B) => C |
| Generic HOF | (item: T, fn: (val: T) => R) => R |
? optional flags on callback arguments |