Check if the typescript class has setter / getter

I have a typescript class that has the following properties:

export class apiAccount  {
    private _balance : apiMoney;
    get balance():apiMoney {
        return this._balance;
    }
    set balance(value : apiMoney) {
        this._balance = value;
    }

    private _currency : string;
    get currency():string {
        return this._currency;
    }
    set currency(value : string) {
        this._currency = value;
    }
    ...

I need to create an empty instance of this class:

let newObj = new apiAccount();

And then check if it has a setter for the "currency", for example. I thought this was exactly what it was doing getOwnPropertyDescriptor, however, apparently, I was wrong:

Object.getOwnPropertyDescriptor(newObj, 'currency')
Object.getOwnPropertyDescriptor(newObj, '_currency')

Both return undefined. But chrome seems to do it! When I hover over an instance, it shows me the properties and shows them as undefined. How can I get a list of these property names or check if a property descriptor exists in the object? enter image description here

+4
source share
1 answer

"" , Object.getOwnPropertyDescriptor - - . : , , , .

currency apiAccount.prototype, newObj. :

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, ... }

-, 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, ... }
+3

All Articles