Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript type for getBoundingClientRect on a variable that could be window or htmlElement

I am trying to have an option for a user to define the viewport of something as an html element and if not fall back to the window. But then I need to get the getBoundingClientRect() of the element if its not the window. So I am doing this right now. I am typing the variable to be HTMLElement | Window but then when I do:

if (opts.viewport === window) {
  viewportHeight = window.innerHeight
  viewportWidth = window.innerWidth
} else {
  const viewportRect = opts.viewport.getBoundingClientRect()
  viewportHeight = viewportRect.height
  viewportWidth = viewportRect.width
}

I get the following error obviously:

Property 'getBoundingClientRect' does not exist on type 'Window | HTMLElement'.
  Property 'getBoundingClientRect' does not exist on type 'Window'.

How would I go about typing this with typescript?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can tell TS what the type is in your else block:



if (opts.viewport === window) {
    viewportHeight = window.innerHeight;
    viewportWidth = window.innerWidth;
} else {
    const viewportRect = (opts.viewport as HTMLElement).getBoundingClientRect();
    viewportHeight = viewportRect.height;
    viewportWidth = viewportRect.width;
}

You can also create and use a type guard:

const isHTMLElement = (target: Window | HTMLElement): target is HTMLElement =>
    (target as HTMLElement).getBoundingClientRect() !== undefined;

if (isHTMLElement(opts.viewport)) {
    const viewportRect = opts.viewport.getBoundingClientRect();
    viewportHeight = viewportRect.height;
    viewportWidth = viewportRect.width;
} else {
    viewportHeight = window.innerHeight;
    viewportWidth = window.innerWidth;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading