最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Chain validation in typescript - Stack Overflow

programmeradmin5浏览0评论

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!

发布评论

评论列表(0)

  1. 暂无评论