115

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'
wonea
  • 4,783
  • 17
  • 86
  • 139
thanhpk
  • 3,900
  • 4
  • 29
  • 36
  • 1
    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. – toskv Apr 24 '16 at 21:46
  • @toskv You are right, it worked when I change target option to 'ES6', my current target is 'ES5' – thanhpk Apr 24 '16 at 21:50
  • I'm having a possibly related issue now, `Type 'Set' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. ts(2569)`. [mayan anger's answer](https://stackoverflow.com/a/48264936/705296) solved it for me. – Joe Sadoski Feb 03 '22 at 18:22

6 Answers6

199

You also can do

Array.from(my_set.values());
mayan anger
  • 2,322
  • 2
  • 11
  • 19
36

if you declare your set this way:

const mySet = new Set<string>();

you will be able to easily use:

let myArray = Array.from( mySet );
OhadR
  • 8,276
  • 3
  • 47
  • 53
27

Fix

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

More

basarat
  • 261,912
  • 58
  • 460
  • 511
4

or simply

const mySet = new Set<string>();
mySet.add(1);
mySet.add(2);
console.log([...mySet.values()]);
WSD
  • 3,243
  • 26
  • 38
3

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

0

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!])
Hugo Ramirez
  • 448
  • 4
  • 6