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
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
Share Improve this question asked Feb 20, 2018 at 13:32 Bad_PanBad_Pan 50814 silver badges24 bronze badges 2- 1 possible duplicate of stackoverflow./questions/35193471/… – Safiyya Commented Feb 20, 2018 at 13:35
- 2 Possible duplicate of How to iterate over a Set in TypeScript? – Ele Commented Feb 20, 2018 at 13:43
3 Answers
Reset to default 4Set 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);
}
You can use fruitSet.forEach( fruit => ... )
If you want to use for..of
, try spread operator: for (const fruit of [...fruitsSet]) { ... }
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
}