Check if typescript class has setter/getter

后端 未结 1 602
一个人的身影
一个人的身影 2021-01-12 00:41

I have a typescript class which has the following properties:

export class apiAccount  {
    private _balance : apiMoney;
    get balance():apiMoney {
               


        
相关标签:
1条回答
  • 2021-01-12 01:00

    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, ... }
    
    0 讨论(0)
提交回复
热议问题