TypeScript疑问:HTMLCollection转数组为何是Element[]而非HTMLElement[]
为什么HTMLCollection转数组后类型是Element[]而非HTMLElement[]?
先看你的代码示例:
const appElem = document.querySelector("#app"); const appChildren = appElem?.children; // HTMLCollection const appChildrenArr = appChildren && Array.from(appChildren); // Element[]
原因主要有两点:
- DOM类型的层级关系:
HTMLElement是Element的子类,DOM规范里Element是所有元素节点的基类,除了常见的HTML元素(比如<div>、<p>),还包含SVG、MathML等非HTML元素(比如<svg>属于SVGSVGElement,它继承自Element但不是HTMLElement)。 - TypeScript的类型定义约束:
Element.children返回的HTMLCollection,在TypeScript的类型声明中默认泛型是Element——因为从标准层面,HTMLCollection允许包含任意类型的Element节点,并非只局限于HTML元素。Array.from()会沿用原集合的元素类型,所以转换后的数组类型就是Element[]。
如果你确定目标元素都是HTML元素,想要得到HTMLElement[]类型,可以用类型断言:
const appChildrenArr = appChildren && Array.from(appChildren) as HTMLElement[];
或者改用querySelectorAll,它支持指定更精确的类型:
const appChildrenArr = appElem ? Array.from(appElem.querySelectorAll<HTMLElement>('*')) : [];
内容的提问来源于stack exchange,提问作者Natalia Davydova
相关产品推荐
相关产品推荐

