解决TS报Type ‘HTMLElement | null’ is not assignable to type ‘HTMLElement’. Type ‘null’ is not assignable to type ‘HTMLElement’
目录
我们在使用 typescript3.9 时,以下代码编译时会提示错误:
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;
以上解决方法总有一种适合你。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 解决TS报Type ‘HTMLElement | null’ is not assignable to type ‘HTMLElement’. Type ‘null’ is not assignable to type ‘HTMLElement’
码云笔记 » 解决TS报Type ‘HTMLElement | null’ is not assignable to type ‘HTMLElement’. Type ‘null’ is not assignable to type ‘HTMLElement’