如何在 TypeScript 中将 Set 转换为 Array

如何在 TypeScript 中将 Set (例如{2,4,6})转换为 Array [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'
79680 次浏览

Fix

  • Use tsconfig.json with "lib": ["es6"]

More

You also can do

Array.from(my_set.values());

if you declare your set this way:

const mySet = new Set<string>();

you will be able to easily use:

let myArray = Array.from( mySet );

or simply

const mySet = new Set<string>();
mySet.add(1);
mySet.add(2);
console.log([...mySet.values()]);

@basarat's answer wasn't sufficient in my case: I couldn't use the spread operator despite having esnext in my lib array.

To correctly enable using the spread operator on sets and other ES2015 iterables, I had to enable the downlevelIteration compiler option.

Here's how to set it via tsconfig.json:

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

You will find a more detailed explanation of this flag in the TS documentation page about compiler options.

Another solution is using the ! post-fix expression operator to assert that its operand is non-null and non-undefined.

You'll find further information in Non-null assertion operator

You can use the spread operator to convert a Set into an Array:

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