Function Composition with Types
Compose functions while preserving type safety.
What Is Composition?
Function composition combines small functions into a bigger one. compose(f, g) produces a function that first applies g, then feeds the result to f.
The Core Definition
Mathematically compose(f, g)(x) = f(g(x)). The functions run right to left: the rightmost runs first.
const compose = (f: (n: number) => number, g: (n: number) => number) =>
(x: number) => f(g(x));
const inc = (n: number) => n + 1;
const dbl = (n: number) => n * 2;
console.log(compose(inc, dbl)(5)); // 11 (5*2 then +1)All lessons in this course
- Pure Functions and Immutability
- Currying and Partial Application
- Function Composition with Types
- Typed pipe and flow Utilities