I have accomplished the same task by using following similar code:
Assuming we have to create a Instance
of classes located under modules
folder.
modules/Calulator.ts
which takes an argument too in constructor:
export class Calculator {
c: number;
constructor(cc: number) {
this.c = cc;
}
sum(a: number, b: number): number {
return a + b + Number(this.c);
}
}
Our InstanceBuilder
class without using eval
(Commented working code using eval
too):
import * as wfModule from "../modules";
export class InstanceBuilder {
getInstance(className: string, ...args: any[]): any {
// TODO: Handle Null and invalid className arguments
const mod: any = wfModule;
if (typeof mod[className] !== undefined) {
return new mod[className](args);
} else {
throw new Error("Class not found: " + className);
}
// Other working methods:
// const proxy: any = undefined;
// const getInstance = (m) => eval("obj = Object.create(m." + className + ".prototype);");
// eval("obj = new mod['" + className + "'](" + args + ")");
// eval("proxy.prototype = Object.create(mod." + className + ".prototype);");
// obj.constructor.apply(args);
}
}
Then, to create the class dynamically, you could do the following:
const instanceBuilder = new InstanceBuilder();
const commandInstance = instanceBuilder.getInstance("Calculator", initArgsValues);
The above solution should work (but not tested it for all the use cases, but should help you get started.)