Typescript - 类型“HTMLElement”上不存在属性“scrollY”

dar*_*ong 2 typescript

我得到了这个方法:

class Foo {
    private getDistanceFromTop (el: HTMLElement): number {
        return el.scrollY || el.scrollTop;
    }
}
Run Code Online (Sandbox Code Playgroud)

参数el是动态的,可以是一个HTMLElement或一个window对象。我尝试Window使用 将其转换为类型as,但出现另一个编译错误:Type 'HTMLElement' cannot be converted to type 'Window'。那么如何修改这段代码才能使其通过 TS 验证而不使用类型呢:any

tos*_*skv 5

HTMLElement 和 Window 是两种不同的类型,因此您可以执行以下操作:

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