TS2339:类型“元素"上不存在属性“样式" [英] TS2339: Property 'style' does not exist on type 'Element'
问题描述
代码如下:
const test = Array.from(document.getElementsByClassName('mat-form-field-infix'));
test.forEach((element) => {
element.outerHTML = '<div class="good-day-today" style="width: 0px;"></div>'; // Please note that this line works fine!
element.style.padding = '10px';
element.style.borderTop = '0';
});
编译时出错:
src/app//.component.ts(101,21) 中的错误:错误 TS2339:属性元素"类型不存在样式".src/app//.component.ts(102,21): 错误 TS2339: 属性样式"元素"类型不存在.
ERROR in src/app//.component.ts(101,21): error TS2339: Property 'style' does not exist on type 'Element'. src/app//.component.ts(102,21): error TS2339: Property 'style' does not exist on type 'Element'.
我该如何解决?
我尝试删除 Array.from...
部分,尝试使用 for of
和 for in
,尝试使用 任何
,但以上是我必须这样做的方式.
I tried to remove the Array.from...
part, tried to use for of
and for in
, tried as any
, but above is the way I have to do it.
推荐答案
你需要一个类型转换:
Array.from(document.getElementsByClassName('mat-form-field-infix') as HTMLCollectionOf<HTMLElement>)
那是因为 getElementsByClassName
只返回 HTMLCollection
,而Element
没有style
属性.HTMLElement
但是确实通过它的 ElementCSSInlineStyle
扩展接口实现它.
That's because getElementsByClassName
only returns HTMLCollection<Element>
, and Element
does not have a style
property. The HTMLElement
however does implement it via it's ElementCSSInlineStyle
extended interface.
请注意,这种类型转换是类型安全的,因为每个 Element
要么是 HTMLElement
,要么是 SVGElement
,我希望您的 SVG Elements 没有类.
Note that this typecast is typesafe in the way that every Element
is either a HTMLElement
or an SVGElement
, and I hope that your SVG Elements don't have a class.
这篇关于TS2339:类型“元素"上不存在属性“样式"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!