首页 > 解决方案 > 在 Typescript 中,如何使用变量作为类名来调用类

问题描述

编辑:私人反馈中的建议答案来自 2013 年,最新答案是 2018 年。我在打字稿游乐场尝试了这些示例,但它们出错了,因此它们可能已过时:

我试图通过首先在变量中获取类名,然后通过调用它来创建一个类对象new。即不是调用 new ActualClassNameActualClasName而是存储在一个变量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()

标签: javascripttypescriptclass

解决方案


推荐阅读