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

2

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Leo...that works.Thanks all of the responses.
2

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

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

Comments

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
}

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.