Skip to content

Instantly share code, notes, and snippets.

@mildronize
Created November 2, 2020 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mildronize/88fff8c30e4547fe7939b414912ee8fa to your computer and use it in GitHub Desktop.
Save mildronize/88fff8c30e4547fe7939b414912ee8fa to your computer and use it in GitHub Desktop.
Creating TypeScript Classes Dynamically - Totally based on Steve Fenton solution (Type Safe)
// 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