document.documentElement 什么时候可以为空?

When can document.documentElement be null?

我遇到过一个 Flow 的用例,当我使用 document.documentElement 时,我需要先对其进行类型优化,因为它有可能在其内置定义中定义为 null。

https://github.com/facebook/flow/blob/8391250177e37a047a33ae728fdbd1138632294a/lib/dom.js#L824

const { documentElement } = document;
if (documentElement instanceof HTMLElement) {
  // continue doing stuff
}

做一个简单的 google 不会产生任何结果,说明为什么会这样。所以我的问题是这个值什么时候可以为空或者它是来自 lib defs 的错误?

我假设它直接来自规范的类型定义。在“空文档”的情况下,Document#documentElement 可以是任何元素或没有元素。您可以构造 Document,因此可能存在不是 HTMLElement 的情况。这似乎有点做作,但我认为这些类型应该解释所有情况。所以如果你有一个文档,它可能会失败。

From MDN:

For any non-empty HTML document, documentElement will always be an <html> element. For any non-empty XML document, documentElement will always be whatever element is the root element of the document.

const d = new Document();
console.log(`document.documentElement: ${document.documentElement instanceof HTMLElement}`);
console.log(`d.documentElement: ${d.documentElement instanceof HTMLElement}`);