Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Set<> collection getting value via index [duplicate]

Hello everyone I'm new in TypeScript and maybe i don't see something obvious but here is my question:

const someSet = new Set();
someSet.add(1)
console.log(someSet[0])

gives me undefined can someone explain me why we cant get value via index? And how can i do that?

like image 336
Symonen Avatar asked Jun 15 '17 09:06

Symonen


Video Answer


2 Answers

You need to use an iterator:

var iterator = someSet.values();
console.log(iterator.next().value);

You can learn more here.

TypeScript doesn't throw when you do someSet[0] because you can also access the properties using the index syntax:

someSet["values"]
like image 66
Remo H. Jansen Avatar answered Sep 18 '22 10:09

Remo H. Jansen


Set is part of ES6, not TypeScript. It's property is to be an iterable collection of unique values though not with a fixed index. Do not rely on indices to access these items since they're not ordered (use an Array instead). If you would like to iterate over a set you can always use someSet.forEach().

like image 31
Raven Avatar answered Sep 21 '22 10:09

Raven