xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript DOM error All In One

TypeScript DOM error All In One

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;
  }

refs

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-04-23 19:45  xgqfrms  阅读(63)  评论(2编辑  收藏  举报