Last active
June 25, 2021 07:51
-
-
Save buddhics/a29ca8ac4a115bdbecbe9a5250017fc0 to your computer and use it in GitHub Desktop.
How to load Typescript classes dynamically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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