139

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'
3
  • 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. Commented Apr 24, 2016 at 21:46
  • @toskv You are right, it worked when I change target option to 'ES6', my current target is 'ES5' Commented Apr 24, 2016 at 21:50
  • 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. Commented Feb 3, 2022 at 18:22

6 Answers 6

237

You also can do

Array.from(my_set.values());
Sign up to request clarification or add additional context in comments.

2 Comments

This should be marked as the correct answer
Well, somehow this didn't work for me... my Set is made of strings surrounded by { } so i don't know what is wrong
48

if you declare your set this way:

const mySet = new Set<string>();

you will be able to easily use:

let myArray = Array.from( mySet );

Comments

26

Fix

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

More

1 Comment

The doc link is invalid.
7

or simply

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

Comments

4

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.