1

I want write a TypeScript function that merges one or more transform functions.

A transform function has this signature:

type Transform<T0, T1> = {
  (arg: T0): T1 | Promise<T1>;
}

And the merge function has this signature:

type Merge = {
  <T0, T1>(f0: Transform<T0, T1>): Transform<T0, T1>;
  <T0, T1, T2>(f0: Transform<T0, T1>, f1: Transform<T1, T2>): Transform<T0, T2>;
  <T0, T1, T2, T3>(f0: Transform<T0, T1>, f1: Transform<T1, T2>, f2: Transform<T2, T3>):
    Transform<T0, T3>;
  // ...
};

Is there a way to write that type so that the function can accept any number of argument?

EDIT:

I want to add some example: Consider these functions:

function toNumber(x: string): number {
  return parseFloat(x);
}
function toString(x: number): string {
  return `${x}`;
}

This call is correct: merge(toNumber, toString).

But if we try to call merge(toNumber, toNumber), the compiler should emit an error because, the first argument returns a number and the second one shall accept a number, not a string.

That is why using any in the function signature cannot work.

Nathan Xabedi
  • 1,097
  • 1
  • 11
  • 18
  • Let me know if it works for you. Link: http://shorturl.at/bltvS – captain-yossarian from Ukraine May 17 '21 at 18:57
  • how about something like this: https://www.typescriptlang.org/play?#code/C4TwDgpgBAZlC8UAUA6NBLAJgawFxQEMA7EASgQD5CSBuAKDoGMB7IgZ2CmAHdmBBAE4BzAK4BbCEWBt8cREnT4i4gEYQBAGijoATEtXry8KgG86UKAIjARAolACM9AL4MW7TsAAWViINESUjKwCMiKUMpiappQwRwC6ERCWmx6scAJSUam5pbWtvZOdM5AA The idea is to use the spread operator (...) to accept any amount of arguments – Yuval May 17 '21 at 19:05
  • @Yuval It works but it does not enforce the type of the arguments. The second argument must be a function that accepts the return type of the first argument... – Nathan Xabedi May 17 '21 at 19:39
  • @captain-yossarian There is nothing at [http://shorturl.at/bltvS](http://shorturl.at/bltvS). – Nathan Xabedi May 17 '21 at 19:44
  • https://www.typescriptlang.org/play?#code/C4TwDgpgBAYgdlAvFAFAQwE4HMBcU1wgCUSAfPoVAD5QAKGA9gLYCWAzhADwEikCwAKEEAzAK5wAxsBYMETCNi4AVKBAAewCHAAmbWHAA0UAEqqNW3foDaAXVIoAdE8xY2eK04fGbRPMZHiUjJyClgQjs7YbtY+UADeglBJUBgQwKIYCC5sggC+goISsmzAKRBsogA2pcjyiijoeCUYLHBYJIjkaEYoAEZ4cKJMvQod5L0kAPSTUFaNUM2t7WQLwC1tPf1Qg8OjKzsjGDZAA – captain-yossarian from Ukraine May 17 '21 at 19:56
  • 1
    See the answer to [the related question](https://stackoverflow.com/questions/53173203/typescript-recursive-function-composition); translating that solution here yields [this code](https://tsplay.dev/WkvV9m). Note that while it's easy to say "an array of one-arg function types where the return type of each element is the argument type of the next element" in English, it's significantly harder to express that as a constraint the compiler can really validate. Depending on your use cases you might just want a series of overloads. – jcalz May 17 '21 at 20:20

0 Answers0