Skip to content

Instantly share code, notes, and snippets.

@buddhics
Last active June 25, 2021 07:51
Show Gist options
  • Save buddhics/a29ca8ac4a115bdbecbe9a5250017fc0 to your computer and use it in GitHub Desktop.
Save buddhics/a29ca8ac4a115bdbecbe9a5250017fc0 to your computer and use it in GitHub Desktop.
How to load Typescript classes dynamically
import { Store } from "./Store";
export class DynamicClass {
constructor(className: string, opts: any) {
if (Store[className] === undefined || Store[className] === null) {
throw new Error(`Class type of \'${className}\' is not in the store`);
}
return new Store[className](opts);
}
}
import { DynamicClass } from "./DynamicClass";
class Main {
constructor() {}
start(): void {
try {
let tesla: any = new DynamicClass('Tesla', 'OpenAI');
console.log(`Type of object \'tesla\': ${tesla.constructor['name']}`);
let audi: any = new DynamicClass('Audi', 'Jarvis');
console.log(`Type of object \'audi\': ${tesla.constructor['name']}`);
} catch (e) {
console.error(e);
}
}
}
new Main().start();
export class Tesla {
constructor(private ai: string) {
console.log(`${ai} is driving Tesla`);
}
}
export class Audi {
constructor(private ai: string) {
console.log(`${ai} is driving Audi`);
}
}
export const Store: any = {
Tesla,
Audi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment