失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Type ‘HTMLElement | null‘ is not assignable to type ‘HTMLElement‘

Type ‘HTMLElement | null‘ is not assignable to type ‘HTMLElement‘

时间:2022-10-20 18:40:42

相关推荐

Type ‘HTMLElement | null‘ is not assignable to type ‘HTMLElement‘

在typescript3.9中,以下代码编译时会提示错误:

const elem : HTMLElement = document.getElementById('someid');// 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;

如果觉得《Type ‘HTMLElement | null‘ is not assignable to type ‘HTMLElement‘》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。