次のようなコードがあります。
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 をオーバーライドできます。