如何在TypeScript中将Set转换为Array

122

如何在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'

1
你编译的目标是什么?Set和Array.from是ES6中添加的,当编译为ES5时不可用。如果你想使用它们,可以尝试使用core.js获取它们的polyfill。 - toskv
@toskv 你是正确的,当我将目标选项更改为“ES6”时,它可以正常工作,我的当前目标是“ES5”。 - thanhpk
我现在遇到了一个可能相关的问题,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解决了我的问题。 - Joe Sadoski
6个回答

209

你也可以做到

Array.from(my_set.values());

4
这应该被标记为正确答案。 - EuberDeveloper
好吧,不知怎么的这对我没用……我的Set由用{ }括起来的字符串组成,所以我不知道哪里出了问题。 - MonneratRJ

38

如果您以这种方式声明您的集合:

const mySet = new Set<string>();

您将能够轻松使用:

let myArray = Array.from( mySet );

26

2
文档链接无效。 - kberg

4
或者简单地
const mySet = new Set<string>();
mySet.add(1);
mySet.add(2);
console.log([...mySet.values()]);

3

在我的情况下,@basarat的回答不够充分:尽管我在lib数组中有esnext,但我无法使用扩展运算符。

为了正确地启用集合和其他ES2015可迭代对象上的扩展运算符,我必须启用downlevelIteration编译器选项。

以下是通过tsconfig.json设置它的方法:

{
  "compilerOptions": {
    "downlevelIteration": true
  }
}

你可以在TS文档中的编译选项页面找到此标志的更详细解释。

0
另一个解决方案是使用后缀表达式运算符来断言其操作数非空且未定义。

您可以在非空断言运算符中找到更多信息。

您可以使用展开运算符将Set转换为Array:

const mySet = new Set(['h','j','l','l']);
console.log([...mySet!])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接