首页 > 解决方案 > $ObjMapi 是否像我认为的那样工作?

问题描述

我无法让$ObjMapi<> 实用程序类型按照我的预期行事。

给定一些像这样的类型:

type TheActionMap = {|
  A: {| type: 'A', payload: number |},
  B: {| type: 'B', payload: string |},
  C: {| type: 'C' |},
|};

这具有作为值一部分的键的冗余。为了简化此代码并帮助执行此规则,我更愿意像这样定义它:

type SimpleActionMap = {|
  A: {| payload: number |},
  B: {| payload: string |},
  C: {||},
|}

// Maps the type so that the Key is added into the value as the `type` property
export type ExpandedActions<A> = $Exact<$ObjMapi<
  A,
  <K, V>(K, V) => {| ...V, type: K |},
>>;

type TheActionMap2 = ExpandedActions<SimpleActionMap>

不幸的是,在我的测试中,这两种类型的行为并不相同。虽然前者在所有情况下都按我的预期工作,但后者错过了一些明显的类型错误,例如:

({
  A: { type: 'A', payload: 'bad' },
  B: { type: 'B', payload: 'foo' },
  C: { type: 'C' },
}: TheActionMap2);

这根本没有类型错误。我在这里想念什么?我不明白它$ObjMapi是如何工作的,还是流程实现中存在错误?

令人震惊的是,我还发现ExpandedActions<SimpleActionMap>and TheActionMap2(后者是前者的别名)的用法在相同的场景中具有不同的行为。这很可能是一个错误,我已在 github 上提交了该错误。

这是一个完整的尝试流程示例,其中包含我所有的测试用例

标签: flowtype

解决方案


推荐阅读