Property 'style' does not exist on type 'Element' in TS

1.报错情况:

当前环境:TS

发生错误的实例:

原因:

通过document.getElementsByClassName函数返回的类型为HTMLCollectionOf<Element>,而Element类型上不存在style属性。需要通过类型断言设置正确的类型。

2. 解决

1.使用document.getElementsByClassName

要解决此错误,使用类型断言将元素键入为 HTMLCollectionOf<HTMLElement>.

const boxes = document.getElementsByClassName(
  'box',
) as HTMLCollectionOf<HTMLElement>;

for (let i = 0; i < boxes.length; i++) {
  boxes[i].style.backgroundColor = 'salmon';
}

2.使用document.querySelector

要解决此错误,使用类型断言将元素键入为 HTMLElement.

const box = document.querySelector('#box') as HTMLElement | null;

if (box != null) {
  box.style.backgroundColor = 'salmon';
}
posted @ 2022-10-11 20:48  青柠i  阅读(122)  评论(0编辑  收藏  举报