C/C++教程

TypeScript DOM error All In One

本文主要是介绍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, 禁止转载

这篇关于TypeScript DOM error All In One的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!