Use spread operator on NodeList in Typescript

后端 未结 1 1833
一生所求
一生所求 2020-12-16 22:11

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 = [...doc         


        
相关标签:
1条回答
  • 2020-12-16 22:36

    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.

    0 讨论(0)
提交回复
热议问题