如何设置一个工厂函数来实现它在Typescript中生成的Class的参数调用签名?

How to Set a Factory Function to Implement the Parameter Call Signature of the Class it Generates in Typescript?

我什至不确定我想做的事情是否可行。我正在使用一个为依赖注入提供装饰器的框架,正确输入下面的代码示例非常混乱:

class Control {
  constructor(
    options: {
      tabIndex?: number
    },
    callbacks: {
      onChange?: (event: any) => void,
    }
  ) {
  
  }
}

@inject(Factory.of(Control))
class Form {
  public GetControl: any;
  public control: Control;
  
  constructor(GetControl: any) {
    this.GetControl = GetControl;
  }
  build() {
    this.control = this.GetControl({tabIndex: 0}, null);
  }
}

有没有一种方法可以设置 GetControl 的类型,而不必像这样在控件 Class 中复制参数定义:

public GetControl: (
    options: {
      tabIndex?: number
    },
    callbacks: {
      onChange?: (event: any) => void,
    }
  ) => Control;

从 TypeScript 2.8 开始,我们可以使用剩余参数中的元组从 class 中获取 GetControl 的类型(读取 here) and conditional types (docs)。

class Control {
  constructor(
    options: {
      tabIndex?: number
    },
    callbacks: {
      onChange?: (event: any) => void,
    }
  ) {

  }
}

// Create a function with the same return type and parameters as a constructor
type Factory<T extends new (...a: any[]) => any> =
  T extends new (...a: infer A) => infer R ? (...a: A) => R : never;

class Form {
  ;
  public control: Control;
  // Shorthand field definition, same as your code but shorter :)
  constructor(public GetControl: Factory<typeof Control>) {
  }
  build() {
    this.control = this.GetControl({ tabIndex: 0 }, null);
  }
}

类型 Factory 将构造函数转换为具有相同参数的函数。我们这样做的方法是使用条件类型的推理行为。如果 T 扩展了一个构造函数类型(它这样做是因为类型约束),我们要求编译器在 A 中放入一个包含所有参数类型的元组 (...a: infer A) 并在 R 构造函数的 return 类型(=> infer R,这将是 class 实例类型)。

使用 AR 我们可以定义想要的函数,使用 return 类型 R 并且我们将构造函数的参数扩展到函数 ((...a: A) => R)