首页 > 解决方案 > 无法将正确键入的成员分配给映射

问题描述

虽然我通常理解 Typescript 错误的原因并且可以修复它们,但这让我感到困惑。

这个操场上,我依靠来自Can I define a Typescript map 的答案,该映射具有与每个值的键对应的值约束?创建具有正确键入属性的地图,但我发现我无法分配成员。

我希望 Typescript 能够推断出它是可分配的。这个错误很奇怪。鉴于该属性是可选的,我希望它接受未定义的,但当它是一个保证匹配约束的具体对象时不会抱怨。在 populateLastActions 中,赋值lastAction[actionType] = action会导致错误。

const lastAction: {
    create?: CreateAction | undefined;
    fulfil?: FulfilAction | undefined;
}
Type 'Action' is not assignable to type 'undefined'.
  Type 'CreateAction' is not assignable to type 'undefined'.(2322)

标签: typescriptundefinedassigndiscriminated-union

解决方案


推荐阅读