[SOLVED] Js immutable – how to flatten a map to a Set<number>

Issue

I have a value shipments that is of a type Map<number, Shipment>, Shipment has a property packageIds which is of a type Set<number>. When I have multiple shipments I would like to go through each shipment, get their packageIds and make a flat new Set with all of the packageIds from each shipment:

shipments.flatMap(shipment => shipment.get('packageIds'))

But, if I do that I get a typescript error:

TS2322: Type 'Set<number>' is not assignable to type 'Iterable<[unknown, unknown]>'.
  The types returned by '[Symbol.iterator]().next(...)' are incompatible between these types. 
  Type 'IteratorResult<number, any>' is not assignable to type 'IteratorResult<[unknown, unknown], any>'.       
  Type 'IteratorYieldResult<number>' is not assignable to type 'IteratorResult<[unknown, unknown], any>'.         
  Type 'IteratorYieldResult<number>' is not assignable to type 'IteratorYieldResult<[unknown, unknown]>'.           
  Type 'number' is not assignable to type '[unknown, unknown]'. 

How can I then get a flat Set when iterating over a map?

Solution

The immutablejs flatMap method of Maps returns another Map. That’s not what you want. Convert to a Set before, discarding the Map keys:

shipments.toSet().flatMap(shipment => shipment.get('packageIds'))

Answered By – Bergi

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *