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

目录
文章目录隐藏
  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'

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;

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

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 解决TS报Type ‘HTMLElement | null’ is not assignable to type ‘HTMLElement’. Type ‘null’ is not assignable to type ‘HTMLElement’

发表回复