Created
November 2, 2020 16:36
-
-
Save mildronize/88fff8c30e4547fe7939b414912ee8fa to your computer and use it in GitHub Desktop.
Creating TypeScript Classes Dynamically - Totally based on Steve Fenton solution (Type Safe)
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
// Credit | |
// https://www.stevefenton.co.uk/2014/07/creating-typescript-classes-dynamically | |
// https://gist.github.com/mfdeveloper/c337408608d6033fde967fc2e76b12c4 | |
interface ObjectKeyString { | |
[key: string]: any; | |
} | |
class InstanceLoader { | |
static getInstance<T>(context: ObjectKeyString, name: string, ...args: any[]): T { | |
const classRef: { new(...args: any[]): any; } = context[name]; | |
if (!classRef) throw new Error(`The class '${name}' was not found`); | |
let instance = Object.create(classRef.prototype); | |
instance.constructor.apply(instance, args); | |
return <T>instance; | |
} | |
} | |
interface ConstructorTypes { | |
userService: string; | |
authService: string; | |
info: Function; | |
} | |
class MyController { | |
constructor(public userService: number, public authService: string) { } | |
info(){ return "hey"} | |
} | |
const store = { | |
MyController: MyController | |
} | |
var example = InstanceLoader.getInstance<ConstructorTypes>(store, 'MyController', 'user service', 'auth Service'); | |
console.log(example.userService); | |
console.log(example.authService); | |
console.log(example.info()); | |
// The output | |
// user service | |
// auth Service | |
// hey |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment