How to iterate over a set in TypeScript?

How do you iterate over a set from TypeScript? for..of does not work:

'Set<string>' is not an array type or a string type 

.forEach unacceptable because it hides this . I would prefer not to do the while loop in the catch try block. What am I missing? Perhaps this is not as awkward as requiring try {while} catch {}.

+15
typescript
source share
5 answers

@SnareChops was basically correct:

 mySet.forEach(function(item){ // do something with "this" }, **this**); 

It works.

I suppose:

 for(item of mySet.values()){ } 

Will work if I don't work with es-shim files that messed up everything for me. But the cushioning material is prescribed by the Angular 2 crew, therefore ¯_ (ツ) _ / ¯

The only thing that worked was:

 for (var item of Arrays.from(set.values())) { } 

or something like that, which is just awful.

+25
source share

You can still use .forEach with the correct this using a regular function instead of the arrow function

 mySet.forEach(function(item){ expect(this).toEqual(item); }); 

Compared with

 class MyClass{ ... doSomething():{ mySet.forEach((item) => { expect(this instanceof MyClass).toEqual(true); }); } } 

Another way of repeating is to use a for loop over values

 for(item of mySet.values()){ ... } 

More information on iterating Set using foreach can be found here.

+2
source share

Extending the highest answer, it is also type safe if we use let for an iteration variable, therefore:

 for (let elem of setOfElems) { ... do anything with elem... } 

This ensures that elem will be of type X if setOfElems been declared as Set<X> .

+2
source share

This worked for me:

 this.mySet.forEach((value: string, key: string) => { console.log(key); console.log(value); }); 

I found it here: Another stack overflow question

+1
source share

You can use for... of in TypeScript if you add "es6" as "lib" in the compiler options and "es6" as the target.

For example (this will be your tsconfig.json):

 { "compilerOptions": { "target": "es6", "lib": [ "es6", "dom" ] }, "exclude": [ "node_modules" ] } 

GitHub related issue: https://github.com/Microsoft/TypeScript/issues/12707

0
source share

All Articles