Higher-order function types help us describe functions that take other functions as inputs or return functions as outputs. This makes our code clearer and safer.
0
0
Higher-order function types in Typescript
Introduction
When you want to pass a function as an argument to another function, like a callback.
When you want a function to return another function, for example, to customize behavior.
When you want to describe complex function shapes in your code for better type checking.
Syntax
Typescript
type FuncType = (arg: number) => string; type HigherOrderFunc = (fn: FuncType) => void; // Or a function returning another function: type ReturnsFunc = () => (x: number) => string;
Use parentheses to clearly show function input and output types.
Higher-order functions can accept or return functions with any signature.
Examples
This function
greet takes a function callback that accepts a string and returns nothing.Typescript
type Callback = (msg: string) => void; function greet(callback: Callback) { callback('Hello!'); }
This function returns another function that adds a fixed number to its input.
Typescript
type Adder = (x: number) => number; function createAdder(a: number): Adder { return (b: number) => a + b; }
This higher-order function takes a function and returns a new function that modifies its result.
Typescript
type Transformer = (fn: (x: number) => number) => (y: number) => number; const doubleThenAddOne: Transformer = (fn) => (y) => fn(y) + 1;
Sample Program
This program defines a higher-order function shout that takes a function to modify a string. We pass a function that changes text to uppercase.
Typescript
type StringModifier = (input: string) => string; function shout(modifier: StringModifier): void { const message = 'hello'; console.log(modifier(message)); } const toUpperCase: StringModifier = (text) => text.toUpperCase(); shout(toUpperCase);
OutputSuccess
Important Notes
Always specify input and output types for functions to get full type safety.
Higher-order function types can be tricky at first, but they make your code flexible and clear.
Summary
Higher-order function types describe functions that take or return other functions.
They help catch errors early by checking function shapes.
Use them to write flexible and reusable code.