为什么 document.body 不是 HTMLBodyElement?

Why is document.body not a HTMLBodyElement?

Visual Studio,提示 document.bodyHTMLElement,而不是 HTMLBodyElement,这是为什么呢? - 我没有找到答案。

class Test {
    documentBody1: HTMLBodyElement;
    documentBody2: HTMLElement;

    constructor(){
        this.documentBody1 = document.body; //wrong
        this.documentBody2 = document.body; //right
    }
}

属性document.body的类型是HTMLElement,但在大多数情况下它指代的对象实际上是HTMLBodyElement.

那么为什么 document.body 没有输入 HTMLBodyElement?因为在某些文档中,它可能指的是一个HTMLFrameSetElementHTMLElementHTMLBodyElementHTMLFrameSetElement 的公共超类型。

规范中的 document.body 有更多内容。


在评论中,一个好问题:

I'm wondering why is there no null? It will be null when document is not loaded yet...

我的猜测是实用主义。在 TypeScript 社区(以及项目本身)中有很多实用主义而不是理想主义。由于人们几乎 从不 运行 代码在 body 出现之前与 DOM 交互,而不是让每个人都添加一个几乎肯定不必要的守卫或使用 document.body 时的非无效断言,定义该 TypeScript 类型的人使用 HTMLElement 而不是 HTMLElement | null。它并不完全正确,但它是正确和有用之间的平衡。