【问题标题】:I want to list all public properties of a Class/Interface我想列出类/接口的所有公共属性
【发布时间】:2016-07-06 10:20:08
【问题描述】:

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

class Car {
    model: string;
}

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

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

【问题讨论】:

标签: typescript


【解决方案1】:

更新的答案(另请参阅 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
  }
}

【讨论】:

  • 此代码错误。 key 的类型永远不会是“函数”,hasOwnProperty 将排除从原型继承的属性。它也不包括已声明但未定义的属性,也不排除私有或受保护的属性。
【解决方案2】:

就像上面评论中已经提到的 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)来区分私有成员和公共成员。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多