Let's define a function called compose that accept two unary functions and return a new function that is a composition of these two functions.

const compose = (f, g) => (x) => f(g(x))

The usage is pretty simple:

const f = (x) => `f(${x})`
const g = (x) => `g(${x})`
const h = compose(f, g)
console.log(h(1)) // "f(g(1))"

We can type the function compose by creating the ComposeFn type:

type ComposeFn = <A, B, R>(f: (x: B) => R, g: (x: A) => B) => (arg: A) => R
const compose: ComposeFn = (f, g) => (x) => f(g(x))
#functional programming#typescript#javascript

📝 Edit this page