I am trying to achieve some recursive chain validation and I am not sure whether it is possible to solve it in typescript.
Imagine you have a Task class like
export class Task<FnInput, FnOutput> {
public constructor(
private operation: (input: FnInput) => Promise<FnOutput>,
private _name: string,
) {}
public get name() {
return this._name;
}
public async run(data: FnInput): Promise<FnOutput> {
return this.operation(data);
}
}
I am looking for a
type Pipeline<...> =...
that satisfies the following conditions:
- it is an array or arrayLike type, if I create an object with it is an array containing tasks
- The first task's input type can be anything
- The second task's input type must be the first task's output
- The third task's input type must be the second task's input type
- and so on...
The closest i could get:
type ValidateChain<
Tasks extends Task<any, any>[],
PrevOutput = any,
> = Tasks extends [Task<infer Input, infer Output>, ...infer Rest]
? [Input] extends [PrevOutput]
? Rest extends Task<Output, any>[]
? Tasks
: never
: never
: Tasks;
export type Pipeline<Tasks extends Task<any, any>[]> =
ValidateChain<Tasks> extends never ? never : Tasks;
However in this case, it did not validated the functions:
const pipeline: Pipeline<Task<any, any>[]> = [
new Task(pipelineItem1, 'pipelineItem1'),
new Task(pipelineItem2, 'pipelineItem2'),
];
async function pipelineItem1(data: { username: string; password: string }) {
return {
username: data.username,
userId: 123,
};
}
async function pipelineItem2(data: { usernamxe: string; password: string }) {
return {
username: data.usernamxe,
userIssd: 123,
};
}
My typescript version is 5.7.3.
Please let me know if you have idea how to implement such types! Have a good day!