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
is transpiled to
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: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:DOM.Iterable
should be specified inlib
compiler option to include suitable typings. Since DOM iterators require browser support, they can be polyfilled in older browsers withcore-js
.