I'm trying to create a function that triggers the class's init
method and returns the instantiated class, but I'm not able to preserve the constructor and class types.
I tried:
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, "");
But the type return only returns the init
method and I also have the error of the parameters not matching the type constructor:
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)