tk挠痒痒网址发布页-秘密武器
历史搜索

解决TS报Type ‘HTMLElement | null’ is not assignable to type ‘HTMLElement’. Typ

游客2025-05-16 11:42:01
目录文章目录
  1. 解决方法 1: 禁用 strict 模式
  2. 解决方法 2: 严格模式下,加个判断
  3. 解决方法 3:使用类型断言(Type Assertion)

我们在使用 typescript3.9 时,以下代码编译时会提示错误:

解决TS报Type ‘HTMLElement | null’ is not assignable to type ‘HTMLElement’.  Type ‘null’ is not assignable to type ‘HTMLElement’ 1

const ViewerDom: HTMLElement = document.getElementById('imgTooles');
//Type 'HTMLElement | null' is not assignable to type 'HTMLElement'. 
//Type 'null' is not assignable to type 'HTMLElement'

如何解决呢?

解决方法 1: 禁用 strict 模式

修改 tsconfig.ts 文件,
将"strict": true, 改为 "strict": false,

解决方法 2: 严格模式下,加个判断

let elem: HTMLElement;
const temp = document.getElementById('imgTooles');
if (temp) {
	elem = temp;
   // ...
}

解决方法 3:使用类型断言(Type Assertion)

const elem: HTMLElement = document.getElementById('imgTooles') as HTMLElement;

以上解决方法总有一种适合你。

本文是由用户"游客"发布,所有内容的版权归原作者所有。没有经过书面许可,任何单位或个人不得以任何形式复制、转载、引用本网站的内容。否则将追究法律责任。

相关专题