18

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.

2

1 Answer 1

29

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.

Sign up to request clarification or add additional context in comments.

7 Comments

works great... nice and clean!
does this work also in nodejs?
@JaumeMussonsAbad: Try it and let me know. Assuming nodejs still uses standard instance creation it should work (of the namespace is correct).
My first result says it doesn't work in nodejs: "ReferenceError: window is not defined".
@isgoed: This was never tested with nodejs so you may have additional namespaces present. Please ask a new question showing your code. Thanks
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.