如何不启用downlevelIteration解决TS2802的HTMLCollection迭代错误?
解决TypeScript错误TS2802:无需启用downlevelIteration处理HTMLCollection遍历
在基于react-shimmer-skeleton包源码开发静态网格加载器时,ESLint严格模式下触发TS2802错误:Type 'HTMLCollection' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher,问题出在使用扩展运算符转换element.children的代码片段:
{element.children ? [...element.children] .map(child => renderElement(child as HTMLElement)) : null }
以下是无需设置downlevelIteration: true的解决方法:
使用Array.from()转换为数组
Array.from()原生支持将类数组对象(如HTMLCollection)转换为标准数组,无需依赖额外编译配置:{element.children ? Array.from(element.children) .map(child => renderElement(child as HTMLElement)) : null }通过for循环手动构建数组
用传统for循环遍历HTMLCollection并手动组装数组,彻底避开类数组对象的遍历兼容性问题:{element.children ? ( (() => { const childrenList: HTMLElement[] = []; for (let i = 0; i < element.children.length; i++) { childrenList.push(element.children[i] as HTMLElement); } return childrenList.map(child => renderElement(child)); })() ) : null}利用Array.prototype.slice.call()转换
借助数组slice方法和call指定上下文,实现类数组到数组的转换:{element.children ? Array.prototype.slice.call(element.children) .map(child => renderElement(child as HTMLElement)) : null }
内容的提问来源于stack exchange,提问作者Nimantha Fernando
相关产品推荐
相关产品推荐

