Course contentsShow
← TypeScript
Lesson 586 of 1,79614. Generics in PracticeFree lesson

Higher-Order Functions

Map, filter, reduce and custom combinators that preserve element and return types.

Higher-Order Functions

What you'll learn: How to write type-safe higher-order functions that preserve element types through operations like map, filter, and reduce.

What Are Higher-Order Functions?

A higher-order function is a function that either takes a function as an argument or returns a function as its result. In TypeScript, generics let us write higher-order functions that preserve type information through the entire pipeline.

Think of it like a factory assembly line: each station (higher-order function) transforms items while keeping track of exactly what type of item is passing through.

Built-in Higher-Order Functions

JavaScript's array methods are classic examples. With TypeScript's generics, they automatically preserve types:

const numbers = [1, 2, 3, 4, 5];

// map transforms each element, preserving type flow
const doubled = numbers.map(n => n * 2); // number[]

// filter narrows based on condition
const evens = numbers.filter(n => n % 2 === 0); // number[]

// reduce combines elements into a single result
const sum = numbers.reduce((acc, n) => acc + n, 0); // number

Writing Custom Higher-Order Functions

You can create your own combinators that maintain type safety:

function pipe<A, B, C>(
  f: (x: A) => B,
  g: (x: B) => C
): (x: A) => C {
  return (x: A) => g(f(x));
}

const addOne = (n: number) => n + 1;
const double = (n: number) => n * 2;

const addOneThenDouble = pipe(addOne, double);
const result = addOneThenDouble(5); // number: 12

The beauty here? TypeScript tracks that A is number, B is number, and C is number, ensuring you can't accidentally chain incompatible functions.

Key Takeaway: Higher-order functions with generics create type-safe transformation pipelines, ensuring that element types and return types flow correctly through each operation without losing type information.