0

I'm been trying to figure out the correct type definitions for the compose function, see the discussion on github and the discussion on discord.

Consider the example below where I've distilled the compose and pipe type definitions into a concise example. The definitions work correctly for pipe, but not for compose despite them being almost identical (only the order of f1 and f2 is different).

function compose2<R0, R1, R2>(
  f2: (a: R1) => R2,
  f1: (a: R0) => R1,
): (a: R0) => R2 {
  return (x: R0) => f2(f1(x));
}

const composeTest = compose2(
  R.defaultTo('fallback'),
  R.nth(1) // << typescript is already confused
)([1, 2]);

function pipe2<R0, R1, R2>(
  f1: (a: R0) => R1,
  f2: (a: R1) => R2,
): (a: R0) => R2 {
  return (x: R0) => f2(f1(x));
}

// correctly number | string
const pipeTest = pipe2(
  R.nth(1),
  R.defaultTo('fallback'),
)([1, 2]);

What I think this boils down to is that typescript is doing it's inference in the order of the code instead of building a type dependency tree and evaluating it in that order. Is this accurate?

Does anyone have an insight into this problem?

lax4mike
  • 4,933
  • 2
  • 18
  • 8
  • We've had so many Q&A's about typing a pipe/compose function here already. TL;DR it isn't feasible in TypeScript yet. You can probably find the other ones just by searching for them online. – kelsny May 16 '23 at 18:34
  • You can check my [article](https://catchts.com/FP-style#compose) and my [answer](https://stackoverflow.com/questions/65057205/typescript-reduce-an-array-of-function/67760188#67760188) and third party [library](https://github.com/drizzer14/fnts) – captain-yossarian from Ukraine May 16 '23 at 18:57
  • See how `fp-ts` defines [pipe](https://github.com/gcanti/fp-ts/blob/master/src/function.ts#L651-L689) – Mulan May 18 '23 at 23:34
  • 1
    Typescript evaluates the types left-to-right which doesn't play nicely with compose which wants to operator right-to-left – cdimitroulas Jul 05 '23 at 12:08
  • I will also recommend fp-ts as the cleanest solution for composition that actually works in TS – Dejan Toteff Jul 25 '23 at 12:16

0 Answers0