0

If i have a tuple, where each element's parameter's type is the type of the return of the previous function:

let arr = [() => 1, x => "hi" + x.toString(), x => ({ prop: x.startsWith("hi") }), ({prop}) => prop]

Can i give such a tuple a type expressing this behavior, without writing out each individual element's type (mention the rule, let the inferrer do the rest)?

Ideally, it would also cause the parameter of the functions to be inferred from the return of the previous function, but i guess that's a really far fetch to ask for.

For tuples of set length (would have to write out a type for every length up to whatever is needed), along with a "small abuse", I could at least check the validity:

type link<R> = Readonly<[(x: any) => R, (x: R) => any]>
let test = [(x: number) => "hi", (x: string) => 3] as const;

// this is abuse, but hey, it infers the generic parameter, instead of having to write it
type X = typeof test extends link<infer R> ? R : never;
let check: X = <any>0;

// Also, this will be problematic regardless.
// let r = 3;
// for (let f of test) {
//     r = f(r);
// }

For arbitrary length, i always get stuck with spread not working on tuples, and recursive types complaining (somewhat reasonably) about cyclic dependency.

Doofus
  • 952
  • 4
  • 19
  • 1
    I'd suggest working with a builder instead of just a tuple... something like [this](https://stackblitz.com/edit/lerugz). The compiler is much better about inferring the types if you break things up this way. If you want I can write these up as an answer. – jcalz Apr 28 '20 at 19:33
  • Thanks, it's an interesting way, maybe i'll use it. As i don't expect any more to come out of this, and the linked topic being indeed really similar, i'll just close this here. – Doofus May 01 '20 at 17:51

0 Answers0