我们在使用 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;
以上解决方法总有一种适合你。