简体   繁体   中英

How to get the Class in constructor with typescript?

I try to set, to empty string, every properties of my classes at instantiate time. But to get ALL the properties, I need to get the "Class" who is instantiate in the constructor. Any help would be much appreciate !

I work with typescript 3.1

  • Any ideas how can I get the Class in the constructor ?
  • Or how can I get a list of all the properties, including the none instantiates ones, only in using "this" and not the Class?

Here the function I'm using to get all properties of a Class.

      Export class Base {
        id: String;
        ...

         constructor() {
           getAllProperties(MyClass) 
             // I would like to have MyClass to be dynamique
         }

      }

       function getAllProps(cls: new (...args: any[]) => any): any[] {   
         // return a list of all Class properties.
       }

I also tried to use Reflect.metadata API but could not got any good results without the Class.

The parent constructor is called before the children constructor, therefore it won't work. You can create the function and call it after the super() function

// Parent
class A1 {
    constructor() {
    }

    protected init() {
        //Get properties here
        console.log(this);
    }
}

// Child
class A2 extends A1 {
    public a;
    public b;

    constructor() {
        super();

        this.a = 1;
        this.b = 2;
        //code here...

        this.init();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM