Home > database >  Js immutable - how to flatten a map to a Set<number>
Js immutable - how to flatten a map to a Set<number>

Time:03-21

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?

CodePudding user response:

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'))
  • Related