获取父类属性列表

时间:2019-10-22 11:40:24

标签: angular typescript

  

有什么办法可以在打字稿中得到这个结果吗?   有没有办法直接从类名称而不是从对象获取父类的属性列表   我的最终目标是获得这个结果

export class A {
    public a: string;
    public b: string;
}
export class B extends A {
    public missingProperty: any;
    public constructor(res: any){
      super();
      this.missingProperty = {};
      this.setMissingProperty(res);
    }
    private setMissingProperty(res: any){
       Object.keys(res).foreach(element => {
           // if property name match i.e a is present in res as well as class B then assign to the same 
           // property name 
           // else assign to missingProperty
       }
    }
}

我想要什么

// test
const temp = {a:'testa', b: 'testb', 0: 23, 1: 34, 2:75}
const b = new B(temp);
// b.b gives testb
// b.a gives testa
// b.missingProperty gives {0: 23, 1: 34, 2:75}

1 个答案:

答案 0 :(得分:1)

TypeScript编译为JavaScript运行时。显然,在类上声明字段不会初始化它:

console.log(new A()) // prints: { __proto__: {...}}
                     // note how it does not print {a: undefined, b: undefined}
                     // so right now you have no idea what properties A has!
console.log(new B()) // prints: { missingProperty: {}, __proto__: { ... } }
                     // you have no idea what properties A has either!

如果您想在运行时知道哪些属性属于对象,那么您的问题本质上不是TypeScript问题-它是 Javascript 问题!

现在,没有办法知道运行时是否存在A中的属性。相反,您可以做的是首先使用A的构造函数初始化这些已知的属性,因此setMissingProperty将会知道B已经具有这些A继承的属性。然后它可以遍历并查找B没有的属性。

class A {
    public a: string;
    public b: string;
    constructor(options) {
      this.a = options.a;
      this.b = options.b;
    }
}
class B extends A {
    public missingProperty: any;
    public constructor(res: any){
      super(res); // B.a, B.b is initialized here
      this.missingProperty = {};
      this.setMissingProperty(res);
    }
    private setMissingProperty(res: any){
      Object.keys(res).forEach(element => {
        if (!Object.prototype.hasOwnProperty.call(this, element)) {
          this.missingProperty[element] = res[element]
        }
      })
    }
}
相关问题