类型“Element”上不存在属性“offsetTop”

703 阅读1分钟

记录一次类型错误的解决方案,ts报错类型“Element”上不存在属性“offsetTop”。

因为ts默认用的是Element,需要声明为HTMLElement

let top = <HTMLImageElement>document.querySelector('.Top');
let _offsetTop = top.offsetTop

或是下面这样

let top = document.querySelector('.Top') as HTMLElement;
let _offsetTop = top.offsetTop

当然如果你用的是angular的话,建议用 ElementRef

import { Component, ElementRef } from '@angular/core';

constructor(
    private elementRef: ElementRef
) {

}
this.elementRef.nativeElement.querySelector('#select_id');