Home > Net >  Define type to array behavior
Define type to array behavior

Time:05-29

I need to crate a type that can hold an array where each element is a function that gets the previous output as an input. For example, a valid array is:

const pipe: SpecialArray = [
    () => string,
    (prev:string) => number,
    (prev:number) => boolean
];

An invalid array would be:

const pipe: SpecialArray = [
    () => string,
    (prev:number) => number, // <-- Here number should be string
    (prev:number) => boolean
];

Is there a way to define such structure in TypeScript?

CodePudding user response:

I believe no, since Array is homogenous, you'll have to define in the form [(a: string) => number, (b: number) => boolean], and you can't really enumerate all (unless a code generator is used).

CodePudding user response:

It is impossible in TypeScript to create standalone type for such kind of array. In order to do that you should create compose function, infer each function from arguments and validate it. Please see my article and questions/answers on SO: first , second, third.

Also you can check this compose function in fnts lib

  • Related