typescript类构造函数基于其函数的args作为参数推断类型

ni65a41a  于 2023-01-27  发布在  TypeScript
关注(0)|答案(2)|浏览(140)

很抱歉,如果标题不是很清楚,但我不知道如何表达我的问题更好。
我有一个Process类:

class Process {
  readonly fn: Function;
  readonly parameters: any | any[]; // doing sth here to have the types inferred based on `fn` args
  nextMessage: Message | null;

  constructor(fn:Function, parameters: any|any[]){
    this.fn = fn;
    this.parameters = parameters;
  }
}

当示例化一个新的过程对象时:

function doTask(task: string){
  console.log(`doing ${task}`);
}
const message = new Process(doTask, "Something");

我想对传递给Message构造函数的parameter进行类型检查,以匹配函数参数的类型。例如,在上面的代码中,如果我传递一个数字而不是字符串,我想得到一个错误。

hxzsmxv2

hxzsmxv21#

最简单的方法是使用一个类型参数,将函数的参数类型表示为元组:

class Process<T extends any[]> {
  readonly fn: (...args: T) => any;
  readonly parameters: T; // doing sth here to have the types inferred based on `fn` args
  
  constructor(fn: (...args: T) => any, parameters: T){
    this.fn = fn;
    this.parameters = parameters;
  }
}

function doTask(task: string){
  console.log(`doing ${task}`);
}
const message = new Process(doTask, ["Something"]);

Playground链接

yeotifhr

yeotifhr2#

为此,您可以使用类型参数:

class Process<F extends Function> {
  readonly fn: F;
  readonly parameters: any | any[]; // doing sth here to have the types inferred based on `fn` args
  nextMessage: Message | null;

  constructor(fn: F, parameters: Parameters<F["apply"]>) {
    this.fn = fn;
    this.parameters = parameters;
  }
}

它所做的正是您所期望的,提取参数类型。
它是这样实现的:

/**
 * Obtain the parameters of a function type in a tuple
 */
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

相关问题