DEV Community

Discussion on: Creating a typed "compose" function in TypeScript

Collapse
 
waynevanson profile image
Wayne Van Son • Edited

I got composable to work the same as pipe: multiple initial arguments.

export function compose<R, F extends (a: R, ...b: any) => R>(
  fn1: F,
  ...fns: Array<(a: R) => R>
) {
  return fns.reduce(
    (prevFn, nextFn) => value => prevFn(nextFn(value)),
    fn1
  ) as F;
}

const a = (v: string, q: number, s: boolean) => v + q;
const b = (v: string) => v;

const c = compose(a, b, b, b, b, b, b);
Enter fullscreen mode Exit fullscreen mode

I can say that I've been wanting to find this post for at least a year!