Currently, I am experimenting with code to create a more streamlined Angular Dialog initializer. This initializer should be passed a constructor function along with its arguments in a type-safe manner. The current implementation works, but it is
- challenging
- less safe than desired
class SomeDialogClass {
name: string;
nachname: string;
id: number;
constructor(name: string, nachname: string, id: number) {
this.name = name;
this.nachname = nachname;
this.id = id;
}
}
// type Constructor = new (...args: unknown[]) => unknown; // <- breaks
type Constructor = new (...args: any[]) => any; // <- This is not ideal. Is there no utility type for "Constructor"?
function createDialog<DialogClass extends Constructor>(classConstructor: DialogClass, ...args: ConstructorParameters<DialogClass>): InstanceType<DialogClass> {
// everything within this function is uncertain due to the use of "any" in Constructor type
return new classConstructor(...args);
}
const instance = createDialog(SomeDialogClass, "John", "Doe", 7);
console.log(instance);
Is there a more elegant solution to achieve this functionality?