Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

ecmascript 6 - Use spread operator on NodeList in Typescript

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...