如何列出给定对象的所有get属性



给出类:

export class Foo
{
#x: number;
#y : number;
constructor()
{
this.#x = 20;
this.#y = 10;
}
public get a(): string { return "baa"; }
public get n(): number { return 20; }
}

如何获取getters属性,即["a", "n"]?我还没有要显示的代码,我已经查看了reflectreflect-metadata,但找不到任何可以列出它们的代码。我使用的是typescript,但javascript解决方案也很受欢迎。

您可以迭代原型(或对象及其每个原型(的属性描述符,并查看描述符是否具有get函数。

const logGetters = obj => {
if (!obj) return;
for (const [key, desc] of Object.entries(Object.getOwnPropertyDescriptors(obj))) {
if (desc.get && key !== '__proto__') console.log(key); // exclude Object.prototype getter
}
logGetters(Object.getPrototypeOf(obj));
};
class Foo {
#x;
#y;
constructor() {
this.#x = 20;
this.#y = 10;
}
get a() {
return "baa";
}
get n() {
return 20;
}
}
const f = new Foo();
logGetters(f);

对于Typescript,只需使用const logGetters = (obj: object) => {进行注释。

您可以filter而不是Object.getOwnPropertyDescriptors

class Foo
{
#x;
#y;
constructor()
{
this.#x = 20;
this.#y = 10;
}
get a()  { return "baa"; }
get n()  { return 20; }
}
const res = Object.entries(Object.getOwnPropertyDescriptors(Foo.prototype))
.filter(([k, d])=>typeof d.get === 'function').map(([k])=>k);
console.log(res);

最新更新