Is there a simple way to instantiate an object when the class name you want to instantiate is in a variable? I'm porting an existing app to TS/Node.js and I have an abstract base class with a class factory where I pass the class type I want in as a parameter, which itself comes from the environment.
I would like to keep the code as close to the original as possible for now, but I don't see an easy way to do this that doesn't require me to e.g. modify the base class every time I add a new child class that inherits from it.
A dumbed down version of the code I want basically looks like this:
export abstract class Foo {
static async get(className : string) : FOO {
if (!FOO._instance) {
FOO._instance = new className();
}
return FOO._instance;
}
}
... then ...
export class Bar extends Foo {
/* stuff */
}
... and finally used as ...
const baz = await Foo.get('Bar');
// baz is now an instance of Bar.
The real code is more complicated than this, but all of it works except the line containing the new className()
and I can't find a way to pass the class name I want to instantiate to new
or some other way of instantiating a class. PHP, Java, Perl, and C# all do this pretty simply, but I can't seem to find a workalike in TS. The closest I've come up with is e.g. a switch statement in the factory getter that knows about all the subclasses, which will work, but isn't exactly optimal.
TIA.