darksoulsong darksoulsong - 29 days ago 11
TypeScript Question

Typescript - Property 'scrollY' does not exist on type 'HTMLElement'

I got this method:

class Foo {
private getDistanceFromTop (el: HTMLElement): number {
return el.scrollY || el.scrollTop;
}
}


The
el
argument is dynamic and can be an
HTMLElement
or an
window
object. I tried to convert it to
Window
type using
as
, but another compilation error appears:
Type 'HTMLElement' cannot be converted to type 'Window'
. So how do I modify this code in order to make it pass TS validation and without using the
:any
type?

Answer

HTMLElement and Window are two different types so you could do something like this:

class Foo {
  private getDistanceFromTop(el: HTMLElement | Window) {
    if (el instanceof Window) {
      return el.scrollY;
    }
    return el.scrollTop;
  }
}