【发布时间】:2020-07-24 14:31:33
【问题描述】:
我有一些这样的代码:
function changeProperty(prototype: Object, propertyKey: string) {
Object.defineProperty(prototype, 'extra', {
get: () => 'added'
});
const existing = Object.getOwnPropertyDescriptor(prototype, propertyKey);
Object.defineProperty(prototype, propertyKey, {
get: () => 'pass'
});
}
class Test {
@changeProperty
get original() { return 'fail'}
}
// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
const x = new Test() as any;
appDiv.innerHTML = `original: ${x.original}<br/>extra: ${x.extra}`;
https://stackblitz.com/edit/typescript-j8s1bq
我观察到extra 属性已成功添加,但我无法覆盖/覆盖/删除现有属性。
我不知道为什么会这样。
如果我使用类装饰器,我可以使用相同的技术来覆盖 getter。
【问题讨论】:
-
装饰器
return不应该是新的描述符吗? -
根据文档和打字,没有。不适用于属性/访问器装饰器
-
显然我在阅读文档时搞砸了,这些文档区分了属性装饰器(应用于普通字段)和访问器装饰器。不同之处在于,我错过了包含当前属性描述符的第三个参数
标签: typescript decorator typescript-decorator propertydescriptor