I am currently working on implementing a feature where users can define the viewport of an HTML element. If no viewport is specified, it should default to the window. However, I need to retrieve the getBoundingClientRect()
property of the element if it's not the window. Here is my current approach: I have defined the variable as HTMLElement | Window
, but encounter an error when trying to access the property in the following code snippet:
if (opts.viewport === window) {
viewportHeight = window.innerHeight
viewportWidth = window.innerWidth
} else {
const viewportRect = opts.viewport.getBoundingClientRect()
viewportHeight = viewportRect.height
viewportWidth = viewportRect.width
}
The error message that I receive is:
Property 'getBoundingClientRect' does not exist on type 'Window | HTMLElement'.
Property 'getBoundingClientRect' does not exist on type 'Window'.
I would like to know how I can properly type this scenario using TypeScript.