1

I have the following weird issue on my code using Typescript 2.6. I 'm trying to loop through a Set of string values but I get the following error and I don't understand why.

'Type 'Set' is not an array type or a string type. '

Here is what I have:

loopThroughSet(): void {

        let fruitSet = new Set()
        .add('APPLE')
        .add('ORANGE')
        .add('MANGO');

        for (let fruit of fruitSet) {
            console.log(fruit);
        }
}

Does anyone knows what's the problem? Thanks in advance

Bad_Pan
  • 488
  • 13
  • 20
  • 1
    possible duplicate of https://stackoverflow.com/questions/35193471/how-to-iterate-over-a-set-in-typescript – Safiyya Feb 20 '18 at 13:35
  • 2
    Possible duplicate of [How to iterate over a Set in TypeScript?](https://stackoverflow.com/questions/35193471/how-to-iterate-over-a-set-in-typescript) – Ele Feb 20 '18 at 13:43

3 Answers3

4

Set are not define in TS, you need to configure TS with es2017.object or convert Set values to array :

for (var item of Array.from(fruitSet.values())) {
  console.log(item);
}
Léo R.
  • 2,620
  • 1
  • 10
  • 22
2

You can use fruitSet.forEach( fruit => ... )

If you want to use for..of, try spread operator: for (const fruit of [...fruitsSet]) { ... }

Mixalloff
  • 827
  • 4
  • 10
0

In my case, I needed to iterate through a range of seven items without defining and using a variable that would be marked as unused by ESLint, and the spread syntax helped a lot.

[...Array(7)].map(() => {
    // some code
});

instead of

for (const _ of range(0, 7)) {
    // Some code
}
Zdravko Kolev
  • 1,569
  • 14
  • 20