Type ‘HTMLButtonElement | null’ is not assignable to type ‘HTMLButtonElement’.
Type ‘null’ is not assignable to type ‘HTMLButtonElement’.ts
problem
// 报错:Type 'HTMLButtonElement | null' is not assignable to type 'HTMLButtonElement'.
// 报错:Type 'null' is not assignable to type 'HTMLButtonElement'.ts
const button:HTMLButtonElement = document.querySelector('button')
reason
button 可能为null 不存在
solution
- 使用断言,表示一定存在
- 使用联合类型,表示可能为null
// [1]
const button = document.querySelector('button') as HTMLButtonElement
// [2]
const button: HTMLButtonElement | null = document.querySelector('button')
文章讲述了在TypeScript中遇到关于`HTMLButtonElement`类型赋值错误的问题,原因是`button`可能为null。解决方案包括使用断言确保存在性,以及使用联合类型明确可能的null值。
559

被折叠的 条评论
为什么被折叠?



