Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Instance Of Class Based On ClassName : string

Before anyone marks this as duplicate please read below,

My scenario doesn't just involve TypeScript but also Angular2.

Objective

I need a method in app.component.ts which takes a string(Class Name) and creates a instance of that. The classes exist in other ts files.

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

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

But Now i have multiple ts files lets say interfaces.ts, classes.ts, otherclasses.ts. Im using export namespace SampleNS{} in interface.ts all works, next in classes.ts using the /// <reference path="interfaces.ts" /> and same namespace SampleNS.

Now my method getWidgetObjectFromClassName(className : string) : Object{} is in xyz.ts, and now which import should i give?, my point being if i say `import {SampleNS} from './interfaces'. The problem here is i can only import a single file's namespace(even though its the same) hence im creating instance is limited to the import of that specific file namespace.

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

like image 628
Pratik Kelwalkar Avatar asked Jul 01 '16 05:07

Pratik Kelwalkar


People also ask

How do you create an instance of a class?

Instantiating a Class When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

How do you create an instance of a class in Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.


1 Answers

Use as with imports like

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

Plunker example

I remember this from another answer but I couldn't find it to give some credit :-/

like image 165
Günter Zöchbauer Avatar answered Sep 30 '22 06:09

Günter Zöchbauer