Q: 如何使用 Array.prototype.filter 过滤数组,且返回正确的类型
A: 传入 filter 的回调函数,返回值手动声明 is.
例:(下面的例子同时使用了 TS 4.0 引入的 labeled tuple)
请关注第 5 行
// 返回一个元素的所有子元素的 offsetLeft 与 clientWidth
const childNodes = document.getElementById('xxx').childNodes;
const childWidths = Array.from(childNodes || [])
.filter((item): item is HTMLElement => item instanceof HTMLElement)
.map((item) => [item.offsetLeft, item.clientWidth] as [offsetLeft: number, clientWidth: number]);
相关文档:TypeScript: Documentation - Narrowing (typescriptlang.org)
错误做法
请关注第 5 行
// 返回一个元素的所有子元素的 offsetLeft 与 clientWidth
const childNodes = document.getElementById('xxx').childNodes;
const childWidths = Array.from(childNodes || [])
.filter<HTMLElement>((item) => item instanceof HTMLElement)
.map((item) => [item.offsetLeft, item.clientWidth] as [offsetLeft: number, clientWidth: number]);
错误原因:item instanceof HTMLELement 仅仅是一个 boolean 值, 无法被自动识别为 一个 is narrowing 操作。