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')