1

How to define first element as type First and extract result of previous element as parameters of next function.

type First = (a: number) => any;
const fns = [
  (a) => a.toString(), // a => number;
  (b) => parseInt(b), // b => string
  (c) => c + 1, // c => number
  (d) => d.toString() // d: number
]

I need a, b, c, d, ...etc have to be defined.

Trọng Nguyễn Công
  • 1,207
  • 1
  • 10
  • 23
  • [Here](https://stackoverflow.com/questions/65319258/how-to-type-pipe-function-using-variadic-tuple-types-in-typescript-4/68513136#68513136) and [here](https://stackoverflow.com/questions/65057205/typescript-reduce-an-array-of-function/67760188#67760188) you will find related questions/answers – captain-yossarian from Ukraine Feb 16 '22 at 08:33
  • If you intend to compose these functions together, then you can une a library like [Ramda.pipe](https://ramdajs.com/docs/#pipe), which will do the inference of types for you (with `@types/ramda` installed) – Didi Bear Feb 16 '22 at 10:26
  • Checkout [the source of Ramda.pipe here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/68c911e5b26e3294c61dbaac500384835f009c18/types/ramda/index.d.ts#L1619) to see how they did it. It quite clunky but it works. – Didi Bear Feb 16 '22 at 10:35

1 Answers1

0

I'm not exactly sure this was your question, but I believe an array of functions makes those functions unrelated to each other from the type system perspective. You can't ensure they will be called in order, so you can't really describe this situation in terms of types. Why not simply:

const fns = [
  (a: number): string => a.toString(), // a => number;
  (b: string): number => parseInt(b), // b => string
  (c: number): number => c + 1, // c => number
  (d: number): string => d.toString() // d: number
]

Or, maybe let's take a step back and explain what problem you are solving - maybe there's a better pattern than an array of functions that need to be called in order? I have a feeling a function composition might be what you're looking for: https://minaluke.medium.com/typescript-compose-function-b7512a7cc012

Greg
  • 5,862
  • 1
  • 25
  • 52