typescript 使用打字稿中的字符串名称创建一个新类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20985117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
create a new class using a string name in typescript
提问by user3171294
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";
我正在编写一个 XML 加载器/解析器(并且是打字稿的新手),我可以很好地加载 XML,但是我正在尝试将 XML 数据动态解析回类/对象。问题是,我想使用字符串变量创建一个类;IE
var classNameString:String = "className";
var newClass:any = new class(classNameString)
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.
从我在互联网上的许多搜索来看,这似乎是不可能的,我将不得不对类名进行硬编码。任何帮助将不胜感激。
回答by Gone Coding
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
:
如果它们在默认命名空间中,您可以简单地使用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.
您现在需要<any>
使用最新的 TypeScript进行演员表,否则您将获得Error TS7017 Build:Element implicitly has an 'any' type because type '{}' has no index signature.