How to iterate over a Set in TypeScript?

后端 未结 5 1888
逝去的感伤
逝去的感伤 2021-01-03 19:36

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

\'Set\' is not an array type or a string type

.for

相关标签:
5条回答
  • 2021-01-03 20:18

    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

    0 讨论(0)
  • 2021-01-03 20:23

    You can use for ... of in TypeScript if you add "es6" as "lib" in your compiler options, and "es6" as target. You may also use "es2015.iterable" in place of "es6" in your lib if that better suits your needs.

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

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

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

    0 讨论(0)
  • 2021-01-03 20:26

    @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.

    0 讨论(0)
  • 2021-01-03 20:37

    Extending the most upvoted answer, it is also type-safe if we use let for the iteration variable, so:

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

    This will guarantee that elem will have the type X, if setOfElems was declared as Set<X>.

    0 讨论(0)
  • 2021-01-03 20:42

    This worked for me:

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

    I found it here: Other Stack Overflow question

    0 讨论(0)
提交回复
热议问题