I've come across a use case with Flow, and when I use document.documentElement
I need to first type refine it because it has the possibility of being null as defined in their built in definitions.
https://github.com/facebook/flow/blob/8391250177e37a047a33ae728fdbd1138632294a/lib/dom.js#L824
const { documentElement } = document;
if (documentElement instanceof HTMLElement) {
// continue doing stuff
}
Doing a simple google does not yield any results for why this is the case. So my question is when can this value be null or is it a mistake from the lib defs?
I would assume it's coming directly from the spec's type definitions. It's possible for Document#documentElement
to be any element or no element in the case of an "empty document". You can construct Document
s, so there could be cases where it isn't an HTMLElement
. It seems a little contrived, but I think the types are supposed to account for all cases. So if you have a empty document, it may fail.
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}`);