如何通过TypeScript中的装饰器获取另一个属性的值

时间:2018-10-16 08:43:10

标签: typescript decorator

export class UmsDictionary {
    public aField = "SUPER";
    @PropertyAlias('aField')
    public dictionary = "dictionary";
}

export function PropertyAlias(name: string) {
 return (target: any, key: string) => {
   Object.defineProperty(target, key, {
     configurable: false,
     get: () => {
       return target[name];
     },
     set: (val) => {}
   })
 }
}

...

const dct = new UmsDictionary();
console.log("VALUE = " + dct.dictionary); //undefined

我试图通过调用字典属性的获取方法来获取aFiled属性的值。我怎么了谢谢

1 个答案:

答案 0 :(得分:1)

target将不是类的实例,而是类本身。要访问字段值,您将需要在get / set函数中使用this而不使用箭头函数:

export class UmsDictionary {
    public aField = "SUPER";
    @PropertyAlias('aField')
    public dictionary = "dictionary";
}

export function PropertyAlias(name: string) {
    return (target: any, key: string) => {
        Object.defineProperty(target, key, {
            configurable: false,
            get: function (this: { [name: string]: any}) {
                return this[name];
            },
                set: function (this: { [name: string]: any}) {
            }
        })
    }
}
const dct = new UmsDictionary();
console.log("VALUE = " + dct.dictionary); //undefined