How can I convert a Set to an Array in TypeScript

ArraysTypescriptSettypescript1.8

Arrays Problem Overview


How can I convert a Set (eg, {2,4,6}) to an Array [2, 4, 6] in TypeScript without writing a loop explicitly ?

I have tried those following ways, all of them work in JavaScript but none of them work on TypeScript

[...set] // ERR: "Type 'Set<{}>' is not an array type" in typescript

Array.from(set) // ERR: Property 'from' does not exist on type 'ArrayConstructor'

Arrays Solutions


Solution 1 - Arrays

You also can do

Array.from(my_set.values());

Solution 2 - Arrays

Fix

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

More

Solution 3 - Arrays

if you declare your set this way:

const mySet = new Set<string>();

you will be able to easily use:

let myArray = Array.from( mySet );

Solution 4 - Arrays

or simply

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

Solution 5 - Arrays

@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.

Solution 6 - Arrays

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!])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthanhpkView Question on Stackoverflow
Solution 1 - Arraysmayan angerView Answer on Stackoverflow
Solution 2 - ArraysbasaratView Answer on Stackoverflow
Solution 3 - ArraysOhadRView Answer on Stackoverflow
Solution 4 - ArraysguzmanojView Answer on Stackoverflow
Solution 5 - ArraysFrancesco MastelloneView Answer on Stackoverflow
Solution 6 - ArraysHugo RamirezView Answer on Stackoverflow