Skip to content

Instantly share code, notes, and snippets.

@mfdeveloper
Created January 6, 2018 16:16
Show Gist options
  • Save mfdeveloper/c337408608d6033fde967fc2e76b12c4 to your computer and use it in GitHub Desktop.
Save mfdeveloper/c337408608d6033fde967fc2e76b12c4 to your computer and use it in GitHub Desktop.

Revisions

  1. mfdeveloper created this gist Jan 6, 2018.
    41 changes: 41 additions & 0 deletions instance-loader.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    /**
    * Creates a dynamic instance of a specific class/prototype.
    * Minor changes from initial solution shared by **Steve Fenton**
    *
    * WARNING: This solution don't works on Angular applications,
    * using JIT (because the webpack don't compiles classes into window object)
    * or AOT (js minification for production build) compilation.
    *
    * @see https://www.stevefenton.co.uk/2014/07/creating-typescript-classes-dynamically/
    */
    export class InstanceLoader {

    static getInstance<T>(context: { [key: string]: any }, 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);

    try {
    instance.constructor.apply(instance, args);
    } catch (err) {
    /**
    * For ES2015(ES6): constructor.apply is not allowed
    */
    if (/Class constructor/.test(err.toString())) {
    instance = class extends classRef {
    constructor(...params: any[]) {
    super(...params);
    }
    };

    return <T>new instance(args);
    }
    }

    return <T>instance;
    }
    }