How do you iterate over a set in TypeScript? for..of does not work:
'Set<string>' is not an array type or a string type
.forEach
is not acceptable, because it hides this
. I'd prefer not to do a while loop in a try catch block. What am I missing? It can't it possibly so clumsy as to require try {while} catch {}.
Use the forEach() method to iterate over a Set in TypeScript. The forEach method takes a function that gets invoked once for each value in the Set object. The forEach method returns undefined . Copied!
You can iterate through the elements of a set in insertion order.
TypeScript includes the for...of loop to iterate and access elements of an array, list, or tuple collection. The for...of loop returns elements from a collection e.g. array, list or tuple, and so, there is no need to use the traditional for loop shown above.
Iterables. An object is deemed iterable if it has an implementation for the Symbol. iterator property. Some built-in types like Array , Map , Set , String , Int32Array , Uint32Array , etc. have their Symbol. iterator property already implemented.
@SnareChops was mostly correct:
mySet.forEach(function(item){ // do something with "this" }, **this**);
This works.
I'm guessing:
for(item of mySet.values()){ }
Would work if I weren't working with es-shim stuff which is messing everything up for me. But the shim stuff is prescribed by the Angular 2 crew so ¯_(ツ)_/¯
The only other thing that worked was:
for (var item of Array.from(set.values())) { }
or something like that, which is just terrible.
You can still use .forEach
with the correct this
by using a regular function instead of an arrow function
mySet.forEach(function(item){ expect(this).toEqual(item); });
Compared to
class MyClass{ ... doSomething():{ mySet.forEach((item) => { expect(this instanceof MyClass).toEqual(true); }); } }
Another way to iterate is to use a for loop over the values
for(item of mySet.values()){ ... }
More information on iterating Set
with foreach can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With