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
    }
}

posted @ 2021-12-15 16:25  。思索  阅读(4878)  评论(0编辑  收藏  举报