How to iterate over a Set in TypeScript?

后端 未结 5 1908
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题