如何让TypeScript在ES6到ES5中构建可迭代内容

How can I get TypeScript to build iterables in ES6 to ES5?

本文关键字:构建 迭代 ES5 TypeScript ES6      更新时间:2023-09-26

我正在尝试用TypeScript在Angular 2中创建一个唯一的用户对象数组。我用简洁优雅的ES6方法创建了一个独特的数组:

  this.users = Array.from(new Set(this.users))

当我将TypeScript构建为ES5:时,我遇到了这个错误

类型为"Set<"{}>"不可分配给类型为"IterableShim<{}>'。类型"Set<"中缺少属性"es6填充程序迭代器";{}>'。

我尝试设置this.users : IterableShim<T>,但IterableShim不是像字符串那样可接受的类型。文档中说String、Array、TypedArray、Map和Set都是内置的可迭代对象,因为它们的原型对象都有一个Symbol.iterator方法。(来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)有没有一种方法可以让TypeScript编译它识别为ES5可迭代的ES6而不会出错?

使用lib选项作为:

"lib": [
  "dom","es6"
]

以下操作很好:

let users = []
users = Array.from(new Set(users))

更多

https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html#lib-选项