Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

123
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda