Overriding property getter from accessor decorator

1.4k views Asked by At

I have some code like this:

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

I observe that the extra property is added successfully, but I am unable to override/overwrite/delete the existing property.

I cannot figure out the explanation for why this is the case.

If I use a class decorator, I am able to use the same technique to override getters.

1

There are 1 answers

0
Kir On

What I missed is that for accessor decorators, you have a PropertyDescriptor passed in as the third argument.

it is sufficient to do the following:


propertyDescriptor.get = () => 'new value';