我想使用 ES6 扩展运算符将 NodeList 转换为数组。我的项目使用 TypeScript,但它抛出了一个错误。
const slides = [...document.querySelectorAll('.review-item')];
这是抛出的错误,error TS2461: Type 'NodeListOf' is not an array type
该代码在 Babel 中是可能的。是否可以在 TypeScript 中使用,或者我是否需要使用其他方法,例如 Object.keys()
?
最佳答案
Spread syntax与可迭代对象一起使用,NodeListOf
就是。 [...document.querySelectorAll('...')]
在 ES6 中有效(只要浏览器或 polyfill 支持 DOM 可迭代对象)。
该问题特定于 TypeScript,它不严格遵循 ES5 目标和更低版本的 ES 规范。默认情况下,Spread 语法仅限于数组,并且
[...document.querySelectorAll('...')];
被转译为
document.querySelectorAll('...').slice();
它会导致错误,并且类型系统会在编译时发出错误。
一种方法是使用 Array.from
(可以在 ES5 环境中进行填充)将可迭代对象转换为数组:
Array.from(document.querySelectorAll('...'));
另一种方法是启用downlevelIteration
compiler option .它强制 TypeScript 2.3 及更高版本根据具有 ES5 目标和更低版本的 ES 规范处理可迭代对象:
Provide full support for iterables in for..of, spread and destructuring when targeting ES5 or ES3.
DOM.Iterable
应该在 lib
编译器选项中指定以包含合适的类型。由于 DOM 迭代器需要浏览器支持,因此可以使用 core-js
在旧版浏览器中填充它们。 .
关于typescript - 在 Typescript 的 NodeList 上使用扩展运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585409/