Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a new class using a string name in typescript [duplicate]

I am writing an XML loader/parser (and new to typescript), I can load the XML fine, however I'm trying to dynamically parse the XML data back into a class/object. The problem is, I would like to create a class using a string variable; ie var classNameString:String = "className";

var newClass:any = new class(classNameString)

from my many searches of the internet it doesn't appear possible, and I'm going to have to hardcode the class names. Any help would be greatly appreciated.

like image 835
user3171294 Avatar asked Jan 08 '14 00:01

user3171294


1 Answers

If you have a specific namespace, for all the class you want to create, you can do this:

var newClass: any = new (<any>MyNamespace)[classNameString](parametersIfAny);

and if they are in the default namespace you can simply use window:

var newClass: any = new (<any>window)[classNameString](parametersIfAny);

Update

You now need to have the <any> cast with latest TypeScript or you get an Error TS7017 Build:Element implicitly has an 'any' type because type '{}' has no index signature.

like image 54
Gone Coding Avatar answered Oct 10 '22 11:10

Gone Coding