I want to list all the public properties of a class / interface

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 a car emit its model property?

+6
source share
2 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 example, the following TypeScript code

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

compiled for:

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

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

You can distinguish between private and public elements using some kind of naming convention (for example, public_member and __private_member ).

+2
source

Updated answer (also see the Crane Weirdo answer on the final JS public / private, to which my answer is not addressed):

 class Vehicle { axelcount: number; doorcount: number; constructor(axelcount: number, doorcount: number) { this.axelcount = axelcount; this.doorcount = doorcount; } getDoorCount(): number { return this.doorcount; } } class Trunk extends Vehicle { make: string; model: string; constructor() { super(6, 4); this.make = undefined; // forces property to have a value } getMakeAndModel(): string { return ""; } } 

Using:

 let car:Trunk = new Trunk(); car.model = "F-150"; for (let key in car) { if (car.hasOwnProperty(key) && typeof key !== 'function') { console.log(key + " is a public property."); } else { console.log(key + " is not a public property."); } } 

Output:

 axelcount is a public property. doorcount is a public property. make is a public property. model is a public property. constructor is not a public property. getMakeAndModel is not a public property. getDoorCount is not a public property. 

Previous answer:

 class Car { model: string; } let car:Car = new Car(); for (let key in car) { // only get properties for this class that are not functions if (car.hasOwnProperty(key) && typeof key !== 'function') { // do something } } 
-3
source

All Articles