首页 > 解决方案 > Property Decorator 不替换定义?

问题描述

我有类似于以下情况的代码,我试图替换基于装饰器的属性

export function DecorateMe() {
    return function(component: any, propertyKey: string) {
        Object.defineProperty(component, propertyKey, {
            get: () => {
                ...
            },
            set: (value: boolean) => {
                ...
            }
        });
    };
}
class Parent {}

@Component()
class Child extends Parent {
    @DecorateMe()
    public property: string;
}

但是在运行时我看到property定义为正常,隐藏get/set添加到原型的方法。

根据 TypeScript文档本教程,我希望它能够工作。

我正在使用 Angular,所以我不确定这是否会产生影响。

标签: angulartypescript

解决方案


看起来你的功能不是属性装饰器。使用以下代码:

export function DecorateMe(component: any, propertyKey: string) {
   var _val = component[propertyKey];

  if (delete component[propertyKey]) {
    Object.defineProperty(component, propertyKey, {
        get: () => {
            console.log("Getter called ", _val);
            return _val;
        },
        set: (value: any) => {
            _val = value;
            console.log("Setter called ", _val);
        }
    });
  }
}

推荐阅读