jeudi 22 décembre 2016

Get property values of properties of types derived from certain type in TypeScript?

I have an abstract class Section that will be used to represent a section of a document that can be either valid or invalid. Such sections can also have embedded sections. A section cannot be valid if it contains an invalid inner section.

I created classes ASection1 and ASection2 for the purpose of use them as inner sections of MySection, to which the validation process is invoked by means of performValidation().

How do I get the properties of types derived from class MySection. I need help on the abstract class reflection logic as commented below.

 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();  

Thanks.





Aucun commentaire:

Enregistrer un commentaire