3

(This is a theoretical use case as a question for thought, thus I have no XY)

I'm trying to make a type for the following array:

const array = [
  () => 1, // 1
  (num: number) => (num + 1) + "", // "2",
  (str: string) => ({ a: "1" + str }), // { a: string }
  (obj: { a: string }) => +obj.a * 5, // 5
  // ..., can stop here or be any length
]

Essentially, the array starts off with a function that takes in no parameters, and then the return type is passed to the next function, and so on.

I am unsure where to start as I can not find anything in the TypeScript documentation for this. Where can I start?

LeoDog896
  • 3,472
  • 1
  • 15
  • 40
  • Such a type is not really possible. You may create a generic function to create and validate an array like this, but you probably need overloads for each amount of elements you want to allow. – Tobias S. Oct 24 '22 at 13:37
  • 1
    This is kind of a pipe function, there is no way of getting around manual typing yet. See https://github.com/gcanti/fp-ts/blob/master/src/function.ts#L410 Or [can we](https://dev.to/ecyrbe/how-to-use-advanced-typescript-to-define-a-pipe-function-381h)? – Ruan Mendes Oct 24 '22 at 17:26
  • Goodness. I'm not really too sure how to resolve a question in this case, but yall two definitely answered my question! Would it be better to make a code generator for that instead, then? – LeoDog896 Oct 24 '22 at 17:30
  • This still isn't really possible directly; no specific array type works the way you want. The best you can get is a generic type that acts as a constraint, as shown in the linked q/a. I'd say arrays aren't the best way to approach chained functions, especially if you don't have a use case that requires arrays. In the absence of a use case I'd recommend [chainable functions as shown here](https://tsplay.dev/mq3okw) before trying to get TS to figure out how to deal with constrained arrays of functions – jcalz Oct 24 '22 at 18:30

0 Answers0