I would like to use the ES6 spread operator to convert a NodeList to an Array. My project uses TypeScript and it's throwing an error.
const slides = [...document.querySelectorAll('.review-item')];
Here is the error that is thrown, error TS2461: Type 'NodeListOf' is not an array type
That code is possible in Babel. Is it possible in TypeScript or do I need to use another method like Object.keys()
?
Spread syntax is used with iterables, which NodeListOf
is. [...document.querySelectorAll('...')]
is valid in ES6 (as long as DOM iterables are supported by the browser or polyfilled).
The problem is specific to TypeScript which doesn't strictly follow ES specs with ES5 target and lower. Spread syntax is limited to arrays by default, and
[...document.querySelectorAll('...')];
is transpiled to
document.querySelectorAll('...').slice();
It will result in error, and type system emits an error on compilation.
One way is to use Array.from
(can be polyfilled in ES5 environment) to convert an iterable to an array:
Array.from(document.querySelectorAll('...'));
Another way is to enable downlevelIteration
compiler option. It forces TypeScript 2.3 and higher to treat iterables according to ES specs with ES5 target and lower:
Provide full support for iterables in for..of, spread and destructuring when targeting ES5 or ES3.
DOM.Iterable
should be specified in lib
compiler option to include suitable typings. Since DOM iterators require browser support, they can be polyfilled in older browsers with core-js
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With