Override element property in TypeScript


I was trying to override element property offsetHeight in my jsdom tests:

const element = document.createElement('div');
element.offsetHeight = 42;

But I received the TypeScript diagnostic error:

error TS2540: Cannot assign to 'offsetHeight' because it is a constant or a read-only property.

To resolve the error, I ended up using Object.defineProperty to override the offsetHeight getter:

Object.defineProperty(element, 'offsetHeight', {
  get() {
    return 42;
  }
});

Now the test compiles and runs!



Please support this site and join our Discord!