Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

121
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!