darksoulsong
darksoulsong

Reputation: 15321

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?

Upvotes: 2

Views: 4686

Answers (1)

toskv
toskv

Reputation: 31600

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

Upvotes: 5

Related Questions