TypeScript——不能將類型“HTMLElement | null”分配給類型“HTMLElement”


前言

針對不能將類型“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
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM