我遇到了一个 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
}
做一个简单的谷歌不会产生任何结果来解释为什么会这样。所以我的问题是这个值什么时候可以为空或者它是 lib defs 的错误?
最佳答案
我假设它直接来自规范的类型定义。 Document#documentElement
是可能的在“空文档”的情况下是任何元素或没有元素。你可以构造 Document
s,所以在某些情况下它可能不是 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}`);
关于javascript - document.documentElement 什么时候可以为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64028461/