Issue
I have this code:
class Category {
constructor(
readonly _title: string,
) { }
get title() {
return this._title
}
}
type Categories = typeof categories
const categories = {
get pets() {
return new class extends Category {
constructor() {
super(
'Pets',
)
}
get dishes() {
return new Category(
'Pets dishes',
)
}
}
},
get cloth() {
return new class extends Category {
constructor() {
super(
'Cloth',
)
}
get accessories() {
return new Category(
'Accessories',
)
}
}
},
}
Object.entries(categories).forEach(([, category]) => {
// Actual logs:
// ["_title"]
// ["_title"]
// Expected logs:
// ["dishes"]
// ["accessories"]
console.log(Reflect.ownKeys(category))
})
Why does Reflect.ownKeys
return something different from what I expect?
How to get a list of getters?
Solution
dishes
and accessories
are not own properties. They are properties defined on the prototype of the anonymous classes. On the other hand, _title
is a own property of the created objects, as that property was added by the constructor (via the super call, in the constructor of Category
).
If you want to only get dishes
and accessories
as a result, then iterate the prototypes:
console.log(Reflect.ownKeys(Object.getPrototypeOf(category))
.filter(prop => prop !== 'constructor'));
Answered By - trincot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.