Typescript ChildNode:`parentElement` and/or `parentNode` 为空?

Typescript ChildNode: `parentElement` and/or `parentNode` is null?

所以这是一个哲学问题。

在 TypeScript 中,Child节点可以parent更少,因为 ChildNode.parentElementChildNode.parentNode 都有一个 null 类型选项。

但是作为Child节点,就其本质而言,它不会有一个parent吗?我可以理解 parentElement 可能是 null,因为它可能来自非元素节点(或者甚至可能)但至少 parentNode 不应该是 non-null?

我知道 DOM spec 中并没有具体说明,但是没有 parent 的 ChildNode 会不会很奇怪?

如果您可能将节点从parent移开,是不是这样?但是这样的事情不会将 ChildNode 的类型更改为普通的 ol' Node?

我真的很想知道你对这个问题的见解,因为它让我有点困惑。

来自 https://developer.mozilla.org/en-US/docs/Web/API/ChildNode:

The ChildNode mixin contains methods and properties that are common to all types of Node objects that can have a parent. It's implemented by Element, DocumentType, and CharacterData objects.

ChildNode 并不表示“该节点当前有一个父节点”。它只是其他类型实现的混合,包括 remove()before()after()replaceWith() 方法。

一个从 Node 继承但 混合在 ChildNode 方法中的类型的示例是 Document。 Document 是一个节点(它的子节点 parentNode 就是它自己)但它永远不能有父节点,所以 document.remove() 会产生编译错误。

Is it like this in the case that you might move the node away from the parent? But wouldn't something like this change the type of the ChildNode, to plain ol' Node?

这不是 TypeScript 的静态类型检查的工作方式——在对象上调用 remove() 等方法不会更改其类型。 (在 JavaScript 中更改对象的原型在技术上可能是可行的,但 TypeScript 不会对此建模。)该节点仍然是与删除之前相同 class 的对象,因此它仍然实现这些方法,即使在节点没有父节点时调用它们可能没有意义。事实上,由于 every Element is a ChildNode,在 element.remove() 之后动态更改类型是没有意义的,因为该元素仍然应该是一个元素。