Home > Software design >  Typescript type for getBoundingClientRect on a variable that could be window or htmlElement
Typescript type for getBoundingClientRect on a variable that could be window or htmlElement

Time:03-25

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?

CodePudding user response:

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;
}
  • Related