【问题标题】:TS2322 - type X is not assignable to type Y, but all fields in Y are contained in XTS2322 - 类型 X 不可分配给类型 Y,但 Y 中的所有字段都包含在 X 中
【发布时间】:2019-03-04 18:03:20
【问题描述】:

所以我在这里使用 react-redux combineReducers。

export interface OurState {widgets: WidgetState; currentView: string;}

export const ourReducer = combineReducers<OurState, ValidAction>({ widgets, currentView });


export type ViewActionType = SwitchViewAction;  
export type ValidAction = WidgetActionType | ViewActionType;

错误消息是 T2322,在 ourReducer 中,说 Type 'ValidAction' is not assignable to type 'SwitchViewAction'

我认为它显然可以分配给这种类型。我怎么错了?

这些动作是调度的动作。

【问题讨论】:

  • 您可以将SwitchViewAction 分配给ValidAction,而不是相反。
  • 如果我写 AnyAction 来代替 ValidAction,还是不行。我当然可以将 AnyAction 分配给 SwitchViewAction?
  • 不,类型的工作方式很热门。您可以将子类型分配给超类型。没有强制转换,您不能将超类型分配给子类型。
  • 嗯,我明白了。为什么“任何”都不起作用,你知道吗?

标签: reactjs typescript redux react-redux


【解决方案1】:

我认为它显然可以分配给这种类型。我怎么错了?

是的。

类型“ValidAction”不可分配给类型“SwitchViewAction”

因为ValidAction 可能是WidgetActionType 类型(因为|)。

【讨论】:

  • 好的,谢谢。有简单的解决方法吗?如果我用 AnyAction 替换 ValidAction,我得到,类型“AnyAction”不可分配给类型“WidgetActionType”
猜你喜欢
  • 2021-03-02
  • 2021-12-06
  • 2021-11-01
  • 2017-12-12
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2020-04-25
相关资源
最近更新 更多