When dealing with the property document.body
, it is important to note that its type is HTMLElement
. However, in many cases, it actually refers to an object that is of type HTMLBodyElement
.
So why isn't document.body
specifically typed as HTMLBodyElement
? This is because in certain documents, it could be referencing an HTMLFrameSetElement
. In essence, HTMLElement
serves as the common supertype for both HTMLBodyElement
and HTMLFrameSetElement
.
For more information, refer to the specification on document.body
.
A question posed by icl7126 in a comment raises an interesting point:
I'm wondering why there is no null value specified? It would make sense when the document has not finished loading...
In my opinion, this choice reflects pragmatism. The TypeScript community (and the project itself) tends to prioritize practicality over idealism. Given that code interactions with the DOM almost never occur before the body
element is present, rather than requiring users to add unnecessary guards or non-null assertions with document.body
, the decision was made to define its type as HTMLElement
instead of HTMLElement | null
. While not entirely perfect, it strikes a balance between accuracy and usability.