javascript - 在 Typescript 中,如何使用变量作为类名来调用类
问题描述
编辑:私人反馈中的建议答案来自 2013 年,最新答案是 2018 年。我在打字稿游乐场尝试了这些示例,但它们出错了,因此它们可能已过时:
我试图通过首先在变量中获取类名,然后通过调用它来创建一个类对象new
。即不是调用 new ActualClassName
,ActualClasName
而是存储在一个变量x
中。所以我想打电话给new x
我,我不确定这是否是正确的方法,但我需要一些接近这个功能的东西。请参阅下面的注释代码。错误在底部(表达式不可构造)
/// associat class names with formId /////
const formNames = {
form1: "F1",
form2: "F2",
};
/// retrieve the name of class, returns a string ///
let formConstructor = formNames["form1"]; // returns f1
/////// define classes
class F1 {
private payload: object;
constructor(payload: object) {
this.payload = payload;
}
myMethod(): string {
return "I have called the F1.myMethod()";
}
}
class f2 {
private payload: object;
constructor(payload: object) {
this.payload = payload;
}
myMethod(): string {
return "I have called the F2.myMethod()";
}
}
/////////// expression not constructable.
let payload = {}
let form = new formConstructor(payload); //How do create new class instance from this ?????
form.myMethod()
解决方案
推荐阅读
- amazon-web-services - AWS Aurora Mysql 故障转移
- c# - Azure.Messaging.ServiceBus SendMessageAsync 每 2 分钟超时一次?
- json - Azure 管道 API 调用门成功标准评估
- javascript - JavaScript 错误:即使 typeof 函数返回“数字”,函数也会返回 NaN
- inno-setup - Inno 设置功能 - 无效的原型
- html - CSS 文本溢出其容器:宽度不适合内容 - 没有宽度的解决方案:适合内容
- javascript - 如何将输入数据持久保存到我的所有表单中
- c# - 嵌套类:在父类中调用子类属性
- image - 如何在 React Native 中预加载图像?
- zsh - 更改默认 Zsh 完成功能