获取TypeScript中从某种类型派生的类型属性的属性值?

时间:2016-12-22 18:13:42

标签: typescript reflection

我有一个抽象类Section,用于表示文档中有效或无效的部分。这些部分也可以有嵌入的部分。如果某个部分包含无效的内部部分,则该部分无效。

我创建了类ASection1ASection2,目的是将它们用作MySection的内部部分,通过performValidation()调用验证过程。< / p>

如何获取从MySection类派生的类型的属性。我需要关于抽象类反射逻辑的帮助,如下所述。

 abstract class Section {

   constructor(public name: string) {
   }

   performValidation(): boolean {

       let result: boolean = true;

       //HELP IS NEEDED HERE!!!
       //get all properties of this instance 
       //whose type inherit from "Section"
       //and execute Validate() on each of them
       //one at a time, if any of them returns
       //false, return false.

       return this.Validate();
   }

   abstract Validate(): boolean; 
 }

 class ASection1 extends Section {
    constructor() {
       super("Section example 1"); 
    }
    Validate(): boolean {
       //validation logic goes here
    }
 }

 class ASection2 extends Section {
    constructor() {
       super("Section example 2"); 
    }
    Validate(): boolean {
       //validation logic goes here
    }
 }

class MySection extends Section {

   constructor() {
      super("My Section"); 
   }

   subsection1: ASection1;
   subsection2: ASection2;

   prop1: number;

   Validate(): boolean {
      return this.prop1 > 100;
   }

}

//run

let mySect = new MySection();
mySect.prop1 = 101;
mySect.subsection1 = new ASection1();
mySect.subsection2 = new ASection2();
mySect.performValidation();  

感谢。

1 个答案:

答案 0 :(得分:0)

如果您有2个或更多相同类型和相同含义的属性每次使用数组而不是每个属性。我将子部分数组添加到每个子部分。在验证中,我检查每个子部分,如果任何子部分验证失败循环返回false,如果没有子部分验证失败验证继续验证自身。

abstract class Section {
    protected subsections: Array<Section> = [];

    constructor(public name: string) {
    }

    performValidation(): boolean {

        let result: boolean = true;

        for (var i = 0; i < this.subsections.length; i++) {
            if (!this.subsections[i].Validate()) {
                return;
            }
        }

        return this.Validate();
    }

    public addSubsection(section: Section) {
        this.subsections.push(section);
    }

    abstract Validate(): boolean; 
 }

 class ASection1 extends Section {
    constructor() {
       super("Section example 1"); 
     }

    Validate(): boolean {
        //validation logic goes here
    }
 }

 class ASection2 extends Section {
    constructor() {
       super("Section example 2"); 
    }
    Validate(): boolean {
        //validation logic goes here
    }
 }

class MySection extends Section {

   constructor() {
      super("My Section"); 
   }

   prop1: number;

   Validate(): boolean {
      return this.prop1 > 100;
   }

}

//run

let mySect = new MySection();
mySect.prop1 = 101;
mySect.addSubsection(new ASection1());
mySect.addSubsection(new ASection2());
mySect.performValidation();