Use compiler option ‘--downlevelIteration‘ to allow iterating of iterators 报错解决

Use compiler option '--downlevelIteration' to allow iterating of iterators 报错解决

最近在一个项目中使用 TS 做单元测试,界面报错如下:

报错分析

具体报错信息如下:Set<number> 不是数组或者字符串类型,不能使用扩展运算符。

error TS2569: Type 'Set<number>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

let newArr:number[] = [...new Set(nums)].sort((a, b) => a - b);

百度后,其他网友也报类似的错误,Map 或者 Set 不能直接使用扩展运算符

TS2569: Type 'Map' is not an array type or a string type. Use compiler. option '- downlevellteration' to allow iterating of iterators.

解决方案1-更改配置 downlevelIteration

按照官方提示,设置 '--downlevelIteration' 是 true,允许以“ ES5”或“ ES3”为目标时,在“ for-of”,传播、解构中为可迭代项提供支持。

把 tsconfig.json 配置文件修改一下即可

{
  "compilerOptions": {
    /* Basic Options */
     "downlevelIteration": true,
/* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
}

解决方案2-更改配置

配置 dom.iterable 和 downlevelIteration 就可以正常运行

tsconfig.json

{
    /*当目标是ES5或ES3的时候提供对for-of、扩展运算符和解构赋值中对于迭代器的完整支持*/
    "downlevelIteration": true,
    "lib": [
      "dom",
      "es5",
      "es6",
      "es7",
      "dom.iterable"
    ]
}
  • 设置 target=es6 的时候,就能正常执行。原因:

注意:如果未指定--lib,则会注入默认的库列表。注入的默认库是: ► For --target ES5: DOM,ES5,ScriptHost ► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

参考链接

tsconfig - Typescript Use compiler option '--downlevelIteration' to allow iterating of iterators error when attempting to spread - Stack Overflow

http://www.voidcn.com/article/p-bccbaiiq-bym.html

TS 常见问题整理(60多个,持续更新ing)-腾讯云开发者社区-腾讯云

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值