我开始编写一个通用的TypeScript函数,该函数将类构造函数作为参数以及构造函数所需的所有参数作为参数,并返回该类的新实例。我的要求之一是返回类型和构造函数参数类型必须由编译器推断。
经过反复试验,我想出了一个可以满足我需要的工作版本(请参阅下文)。但是,有没有更好的方法来实现这一目标?
function instantiate<Params extends any[], Instance>(
ctor: new (...args: Params) => Instance, ...args: Params
) {
return new ctor(...args);
}
示例用法:
class Circle {
constructor(public radius: number) {}
}
class Rectangle {
constructor(public width: number, public height: number) {}
}
const circle = instantiate(Circle, 5);
const rectangle = instantiate(Rectangle, 3, 7);
您可以通过使用ConstructorParameters
和ConstructorParameters
实用程序类型来简化泛型类型的使用:
InstanceType