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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…