I have defined an abstract BaseClass
in a NodeJS Typescript project and I have a list of derived classes that implement and extend this BaseClass
.
// baseModule.ts
export abstract class BaseClass {
constructor() {}
abstract method(): void;
}
export interface ModuleConstructor<T extends BaseClass> {
new (): T
}
export function createModule<T extends BaseClass>(type: ModuleConstructor<T>): T {
return new type();
}
I am trying to find a way to programmatically at runtime create an instance of one of these classes.
The constraint here is that I would like to be able to drop a new myDerivedClass.ts
file into my project folder and have it be automatically included in a list of available modules at runtime.
The developer workflow would be 1) create new file myNewModule.ts
2) create and export a class that extends BaseClass
3) save myNewModule.ts
to ./myModules
// ./myModules/myNewModule.ts
export class MyModule extends BaseClass {
constructor() {
super()
}
method() {
//Do something custom
}
}
The runtime flow (ideally without having to rebuild) would be 1) User selects from a list of available modules 2) createModule
Factory function creates a new instance of chosen module and passes as an instance of
// someOtherClass.ts
const modules = require('./myModules/*') //<- Something to this effect
import { BaseClass, createModule, ModuleConstructor } from './BaseClass'
export class SomeOtherClass {
public mod: BaseClass
constructor(mod: ModuleConstructor) {
this.mod = createModule(mod)
}
}
for (let m in modules) {
console.log(modules[m].name);
}
let someObj = SomeOtherClass(modules[m]);
someObj.mod // <- instance of derived class.