How can I convert a Set to an Array in TypeScript

65,613

Solution 1

Fix

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

More

Solution 2

You also can do

Array.from(my_set.values());

Solution 3

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

or simply

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

Solution 5

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

Share:
65,613

Related videos on Youtube

thanhpk
Author by

thanhpk

Just a student

Updated on July 08, 2022

Comments

  • thanhpk
    thanhpk almost 2 years

    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'
    
    • toskv
      toskv about 8 years
      what target are you compiling to? Both Set and Array.from were added in ES6 and are not available when compiling to ES5. If you want to use them you can try using core.js to get polyfils for them.
    • thanhpk
      thanhpk about 8 years
      @toskv You are right, it worked when I change target option to 'ES6', my current target is 'ES5'
    • Joe Sadoski
      Joe Sadoski over 2 years
      I'm having a possibly related issue now, 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 solved it for me.
  • EuberDeveloper
    EuberDeveloper over 3 years
    This should be marked as the correct answer
  • kberg
    kberg over 2 years
    The doc link is invalid.
  • MonneratRJ
    MonneratRJ about 2 years
    Well, somehow this didn't work for me... my Set is made of strings surrounded by { } so i don't know what is wrong