Js immutable - 如何将地图展平为 Set<number>
Js immutable - how to flatten a map to a Set<number>
我有一个 Map<number, Shipment>
类型的货件,货件有一个 属性 packageIds
类型 Set<number>
。当我有多批货物时,我想检查每批货物,得到他们的 packageIds
并用每批货物的所有 packageIds
制作一个新的平面集:
shipments.flatMap(shipment => shipment.get('packageIds'))
但是,如果我这样做,我会收到打字稿错误:
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]'.
如何在遍历地图时获得平面集?
之前的immutablejs flatMap
method of Map
s returns another Map
. That's not what you want. Convert to a Set
,丢弃了Map
键:
shipments.toSet().flatMap(shipment => shipment.get('packageIds'))
我有一个 Map<number, Shipment>
类型的货件,货件有一个 属性 packageIds
类型 Set<number>
。当我有多批货物时,我想检查每批货物,得到他们的 packageIds
并用每批货物的所有 packageIds
制作一个新的平面集:
shipments.flatMap(shipment => shipment.get('packageIds'))
但是,如果我这样做,我会收到打字稿错误:
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]'.
如何在遍历地图时获得平面集?
之前的immutablejs flatMap
method of Map
s returns another Map
. That's not what you want. Convert to a Set
,丢弃了Map
键:
shipments.toSet().flatMap(shipment => shipment.get('packageIds'))