在typescript3.9中,以下代码编译时会提示错误:
const elem : HTMLElement = document.getElementById('xxx');
// Type 'HTMLElement | null' is not assignable to type 'HTMLElement'
解决方法1:禁用strict模式 修改tsconfig.ts文件,
"strict": true, ---> "strict": false,
解决方法2: 严格模式下,加个判断
let elem: HTMLElement;
const temp = document.getElementById('someid');
if (temp) {
elem = temp;
// ...
}
解决方法3:使用类型断言(Type Assertion)
const elem : HTMLElement = document.getElementById('someid') as HTMLElement;