我正在尝试创建一个触发类init
方法并返回实例化类的函数,但我无法保留构造函数和类类型。
我试过了:
class Test {
constructor(a: number, b: string, c?: number[]) {}
protected init() {}
}
export function instantiateWithInit<Type extends new (args: any) => { init: () => any }>(
clazz: new (args: ConstructorParameters<Type>) => InstanceType<Type>,
...args: ConstructorParameters<Type>
) {
const instance = new clazz(args);
instance.init();
return instance;
}
instantiateWithInit(Test, "");
但是类型返回只返回init
方法,我也有参数不匹配类型构造函数的错误:
Argument of type 'typeof Test' is not assignable to parameter of type 'new (args: [args: any]) => { init: () => any; }'.
Types of construct signatures are incompatible.
Type 'new (a: number, b: string, c?: number[]) => Test' is not assignable to type 'new (args: [args: any]) => { init: () => any; }'.ts(2345)