create a new class using a string name in typescript

class, parsing, typescript

Solution

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.`

Problem

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.

Original source

Related problems