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?
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"]
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()
.
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