前言
針對不能將類型“HTMLElement | null”分配給類型“HTMLElement” 錯誤,可根據實際情況使用!
進行處理或者使用as
進行斷言;
內容
出錯代碼
class Food{
element: HTMLElement;
constructor() {
// 出錯地方 | 因為有可能獲取不到food
this.element = document.getElementById('food')
}
}
解決方法
!
class Food{
element: HTMLElement;
constructor() {
// 因為food本身是我們定義,所以不存在獲取不到的情況,因此!用來表示排除null和undefined
this.element = document.getElementById('food')!
}
}
as
class Food{
element: HTMLElement;
constructor() {
this.element = document.getElementById('food') as HTMLElement
}
}