Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to list all public properties of a Class/Interface

Tags:

typescript

Using TypeScript we can define classes and their public properties. How can I get a list of all public properties defined for a class.

class Car {
    model: string;
}

let car:Car = new Car();
Object.keys(car) === [];

Is there a way to make Car emit its model property?

like image 819
Khanh Hua Avatar asked Mar 19 '16 17:03

Khanh Hua


1 Answers

Like Aaron already mentioned in the comment above, public and private members look the same in Javascript, so there cannot be a method that distinguishes between them. For instance, the following TypeScript Code

class Car {
    public model: string;
    private brand: string;

    public constructor(model:string , brand: string){
        this.model = model;
        this.brand = brand;
    }
};

is compiled to:

var Car = (function () {
    function Car(model, brand) {
        this.model = model;
        this.brand = brand;
    }
    return Car;
}());
;

As you can see, in the compiled JavaScript Version, there is absolutely no difference between the members model and brand, event though one of them is private and the other one is public.

You could distinguish between private and public members by using some naming convention (For instance, public_member and __private_member).

like image 160
Moritz Avatar answered Sep 22 '22 07:09

Moritz