网站搜索

typescript - 是否可以通过反射实例化泛型类型的属性?


我正在尝试创建一个抽象类,它通过迭代传入构造函数的 JSON 风格对象来初始化 T 类的属性。

 abstract class JSONClass<T> {
  // Receive a JSON object implementing all T properties
  constructor(json: JSONClassDictionary<T>) {
    this.fromJSON(json);
  }


  fromJSON(json: JSONClassDictionary<T>) {
    for (let key in json){
      let prop = this[key];
      if (prop is not a class) {  <// -- 1) Determine whether it's a class
        this[key] = prop;
      }
      else{
        const constructor = getConstructorOf(T[key]) // <-- 2) Get constructor of T[Key] property. This is no-sense to compiler
        this[key] = new constructor(prop)
      }
    }
  }
}

问题在于 T 可能有一些不是原始类型的属性,并且需要初始化。

真实案例示例及调用:

class UserRole extends JSONClass<UserRole> {
  id;
  name;
  permissionGroup: PermissionGroup;

}

const role = UserRole({
  id: 1,
  name: "Admin",
  permissionGroup: {// <-- This will be converted to PermissionGroup() in fromJSON
    id: 1,
    action: ".."  
  }
})

这意味着当 fromJSON 正在迭代属性 permissionGroup 时,它 不应 执行 this[key]=prop;,而应执行 this[key]=new PermissionGroup(prop)。

我在代码注释中显示的第(1)点和第(2)点遇到了问题,具体在:

  1. 能够确定我在 json 中迭代的键是否是 T 的一个 可实例化类属性,而不是原始类型;

  2. 如果为真,T 的 initialize 属性。

这是可实现的吗?