在Typescript中的NodeList上使用传播运算符 [英] Use spread operator on NodeList in Typescript

查看:560
本文介绍了在Typescript中的NodeList上使用传播运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ES6扩展运算符将NodeList转换为数组.我的项目使用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')];

这是引发的错误,错误TS2461:类型'NodeListOf'不是数组类型

该代码在Babel中是可能的.可以在TypeScript中使用还是我需要使用其他方法,例如Object.keys()?

That code is possible in Babel. Is it possible in TypeScript or do I need to use another method like Object.keys()?

推荐答案

扩展语法与可迭代对象一起使用,NodeListOf就是可迭代对象. [...document.querySelectorAll('...')]在ES6中有效(只要浏览器支持或可填充DOM可迭代).

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).

问题是特定于TypeScript的,它没有严格遵循ES5或更低版本的ES规范.默认情况下,传播语法仅限于数组,并且

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('...')];

被移植到

document.querySelectorAll('...').slice();

这将导致错误,并且类型system会在编译时发出错误.

It will result in error, and type system emits an error on compilation.

一种方法是使用Array.from(可以在ES5环境中进行填充)将可迭代对象转换为数组:

One way is to use Array.from (can be polyfilled in ES5 environment) to convert an iterable to an array:

Array.from(document.querySelectorAll('...'));

另一种方法是启用 downlevelIteration编译器选项.它强制TypeScript 2.3或更高版本根据ES规范以及ES5目标以下的ES规范来处理可迭代对象:

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:

在针对ES5或ES3时,在for.of,传播和销毁中提供对可迭代项的完全支持.

Provide full support for iterables in for..of, spread and destructuring when targeting ES5 or ES3.

DOM.Iterable应该在lib编译器选项中指定,以包括适当的类型.由于DOM迭代器需要浏览器支持,因此可以使用 core-js .

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.

这篇关于在Typescript中的NodeList上使用传播运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆