Creating an instance of a class based on ClassName: string

Before anyone marks this as a duplicate, read below.

My script uses not only TypeScript, but also Angular2.

goal

I need a method in app.component.ts that takes a string (Class Name) and instantiates this. Classes exist in other ts files.

Now in the use case: I have a getWidgetObjectFromClassName(className : string) : Object{} method, which should return instances of a class name that is in string format. Now the problem is

I tried using NameSpace and doing let instance = new SampleNS['OtherName'](); (SampleNS - namespace), works fine in the case of a single file.

But now I have some ts files, say interface.ts, classes.ts, otherclasses.ts. Im using export namespace SampleNS{} in the .ts interface, everything works, then in .ts classes using /// <reference path="interfaces.ts" /> and the same SampleNS namespace.

Now my getWidgetObjectFromClassName(className : string) : Object{} method is in xyz.ts, and now what import should I give ?, my point is if I say `import {SampleNS} from './interfaces'. The problem here is that I can only import one file namespace (albeit the same), therefore, an im instance is created in a limited way to import this particular file namespace.

Link Plunker https://plnkr.co/edit/pt90F34KPsGoHDpSUQFD?p=preview

+5
source share
2 answers

Use as with import e.g.

 import * as widgets from './lib'; ... this.widgetInstance = new widgets[className](); 

Plunger example

I remember this from another answer, but I could not find it to pay tribute: - /

+7
source

You can use eval to create an object from the class name:

 class SomeClass { x: number; y: number; constructor() { this.x = this.y = 1; } } function getWidgetObjectFromClassName(className : string) : {} { return eval("new " + className + "();"); } console.log("%o", getWidgetObjectFromClassName("SomeClass")); 

Playground here

+2
source

All Articles