Property 'style' does not exist on type 'Element'.ts(2339)
const dom = document.querySelector(selector); // const dom: Element | null // const dom = document.querySelector(selector) as Element; // const dom = document.querySelector(selector) as NodeListOf<HTMLElement>; if (dom) { dom.style.background = background; // ❌ Property 'style' does not exist on type 'Element'.ts(2339)` }
HTMLElement
// ✅ <HTMLElement> const dom = document.querySelector<HTMLElement>(selector); if (dom) { dom.style.background = background; }
// <HTMLElement> ✅ const dom = <HTMLElement>document.querySelector(selector); if (dom) { dom.style.background = background; }
// ✅ as HTMLElement; const dom = document.querySelector(selector) as HTMLElement; if (dom) { dom.style.background = background; }
HTMLCollectionOf
& NodeListOf
// ✅ HTMLCollectionOf<HTMLElement> const doms = document.querySelectorAll(selector) as HTMLCollectionOf<HTMLElement>; if (doms) { doms[0].style.background = background; }
// ✅ NodeListOf<HTMLElement> const doms = document.querySelectorAll(selector) as NodeListOf<HTMLElement>; if (doms) { doms[0].style.background = background; }
https://stackoverflow.com/questions/58773652/ts2339-property-style-does-not-exist-on-type-element
https://github.com/Microsoft/TypeScript/issues/16920
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载