我想列出类/接口的所有公共属性

时间:2016-03-19 17:50:32

标签: typescript

使用TypeScript,我们可以定义类及其公共属性。如何获取为类定义的所有公共属性的列表。

class Car {
    model: string;
}

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

有没有办法让Car发出model属性?

2 个答案:

答案 0 :(得分:3)

就像Aaron在上面的评论中已经提到的那样,公共和私人成员在Javascript中看起来是一样的,所以没有一种方法可以区分它们。例如,以下TypeScript代码

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

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

编译为:

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

正如您所看到的,在编译的JavaScript版本中,成员modelbrand之间绝对没有区别,虽然其中一个是私有的,另一个是公共的。

您可以使用某些命名约定来区分私有成员和公共成员(例如,public_member__private_member)。

答案 1 :(得分:-4)

更新的答案(另请参阅Crane Weirdo关于最终JS公共/私人的回答,我的回答并未解决):

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 "";
    }
}

用法:

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.");
  }

}

输出:

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.

上一个回答:

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
  }
}