I have a typescript class which has the following properties:
export class apiAccount {
private _balance : apiMoney;
get balance():apiMoney {
The "problem" is that Object.getOwnPropertyDescriptor
- as the name implies - only returns descriptors of an object's own properties. That is: only properties that are directly assigned to that object, not those that are from one of the objects in its prototype chain.
In your example, the currency
property is defined on apiAccount.prototype
, not on newObj
. The following code snippet demonstrates this:
class apiAccount {
private _currency : string;
get currency():string {
return this._currency;
}
set currency(value : string) {
this._currency = value;
}
}
let newObj = new apiAccount();
console.log(Object.getOwnPropertyDescriptor(newObj, 'currency')); // undefined
console.log(Object.getOwnPropertyDescriptor(apiAccount.prototype, 'currency')); // { get, set, ... }
If you want to find a property descriptor anywhere in an object's prototype chain, you'll need to loop with Object.getPrototypeOf
:
function getPropertyDescriptor(obj: any, prop: string) : PropertyDescriptor {
let desc;
do {
desc = Object.getOwnPropertyDescriptor(obj, prop);
} while (!desc && (obj = Object.getPrototypeOf(obj)));
return desc;
}
console.log(getPropertyDescriptor(newObj, 'currency')); // { get, set, ... }