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

Kha*_*Hua 6 typescript

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

class Car {
    model: string;
}

let car:Car = new Car();
Object.keys(car) === [];
Run Code Online (Sandbox Code Playgroud)

有没有办法让汽车发出model财产?

Joh*_*nko -4

更新的答案(另请参阅 Crane Weirdo 关于最终 JS public/private 的答案,我的答案没有解决):

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 "";
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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

}
Run Code Online (Sandbox Code Playgroud)

输出:

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.
Run Code Online (Sandbox Code Playgroud)

之前的回答:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这段代码是错误的。“key”的类型永远不会是“function”,并且“hasOwnProperty”将排除从原型继承的属性。它还不包括已声明但未定义的属性,也不排除私有或受保护的属性。 (6认同)