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

vic*_*pro 3 decorator typescript

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) => {}
   })
 }
}
Run Code Online (Sandbox Code Playgroud)

...

const dct = new UmsDictionary();
console.log("VALUE = " + dct.dictionary); //undefined
Run Code Online (Sandbox Code Playgroud)

我试图通过调用字典属性的 getter 来获取属性 aFiled 的值。我的错误是什么?谢谢

Tit*_*mir 5

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

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
Run Code Online (Sandbox Code Playgroud)

  • @vicpro `this: ..` 只是一个类型注释,没有为此生成 JS,这只是为了当我们索引到 `this`(`this[name]`) 时 TS 不会抱怨,就像这样我们使用严格的。`this` 默认由 JS 运行时传入 getter 函数,这就是它的工作方式.. (2认同)