I've been working on a function that is supposed to execute the init
method of a class and then return an instance of that class. However, I'm running into issues with maintaining the constructor and class types.
This is what I have tried so far:
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, "");
However, the return type only includes the init
method and I'm also encountering an error related to parameter matching in 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)