【发布时间】:2016-08-18 04:07:26
【问题描述】:
如何在 TypeScript 中将 Set(例如 {2,4,6})转换为数组 [2, 4, 6] 而无需显式编写循环?
我已经尝试了以下这些方法,它们都可以在 JavaScript 中使用,但它们都不能在 TypeScript 中使用
[...set] // ERR: "Type 'Set<{}>' is not an array type" in typescript
Array.from(set) // ERR: Property 'from' does not exist on type 'ArrayConstructor'
【问题讨论】:
-
你要编译到什么目标? Set 和 Array.from 都是在 ES6 中添加的,在编译到 ES5 时不可用。如果你想使用它们,你可以尝试使用 core.js 为它们获取 polyfils。
-
@toskv 你说得对,当我将目标选项更改为“ES6”时它起作用了,我当前的目标是“ES5”
-
我现在遇到了一个可能相关的问题,
Type 'Set<string>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. ts(2569)。 mayan anger's answer 帮我解决了。
标签: arrays typescript set typescript1.8