微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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


Flag Counter


©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐