TypeScript和Redux:为什么需要添加`| | undefined`到我的Reducer状态类型?

时间:2019-04-22 17:07:20

标签: javascript typescript redux

为什么我不能只像这样简单地键入我的reducer,而不必在redux状态类型中添加“ | undefined”?

const reducer: Reducer<ReduxState> = function(state: ReduxState, action: any) ...

额外上下文::::

这可以正常工作:

export const reducer: Reducer<ReduxState | undefined> = function (
    state: ReduxState | undefined, 
    action: any
) {
    return state
}
export default reducer

但是,当从fxn中删除状态参数“ undefined”时,它不会:

export const reducer: Reducer<ReduxState | undefined> = function (
    state: ReduxState, 
    action: any
) {
    return state
}
export default reducer

哪个错误:

Type '(state: ReduxState, action: any) => ReduxState' is not assignable to type 'Reducer<ReduxState | undefined, AnyAction>'.
  Types of parameters 'state' and 'state' are incompatible.
    Type 'ReduxState | undefined' is not assignable to type 'ReduxState'.
      Type 'undefined' is not assignable to type 'ReduxState'.ts(2322)

或者这个:

export const reducer: Reducer<ReduxState> = function (
    state: ReduxState | undefined, 
    action: any
) {
    return state
}
export default reducer

给出的错误消息为:

Type '(state: ReduxState | undefined, action: any) => ReduxState | undefined' is not assignable to type 'Reducer<ReduxState, AnyAction>'.
  Type 'ReduxState | undefined' is not assignable to type 'ReduxState'.
    Type 'undefined' is not assignable to type 'ReduxState'.ts(2322)

最后,这也不起作用:

import {ReduxState, ReduxAction, ReduxActionType} from './types'
import {Reducer} from 'redux'

export const reducer: Reducer<ReduxState> = function (
    state: ReduxState, 
    action: any
) {
    return state
}
export default reducer

错误消息为:

Type '(state: ReduxState, action: any) => ReduxState' is not assignable to type 'Reducer<ReduxState, AnyAction>'. Types of parameters 'state' and 'state' are incompatible. Type 'ReduxState | undefined' is not assignable to type 'ReduxState'. Type 'undefined' is not assignable to type 'ReduxState'.ts(2322)

TL; DR:Typescript对我的Reducer不满意,除非我在Reducer<ReduxState|undefined>function(state: ReduxState | undefined)中都明确允许“ ReduxState | undefined”类型。

1 个答案:

答案 0 :(得分:3)

由于初始状态,前一个状态未定义。因此,您的函数必须能够将state处理为undefined,这就是第一个错误告诉您的内容。

第二个版本不起作用,因为您return state且可能是未定义的(因为您不检查它是否未定义),因此该函数的返回类型(即Reducer的泛型参数也必须未定义。您可以避免这种情况:

  if(state === undefined)
     return { /*...*/ };
  else return state;

然后Reducer<ReduxState>将正确描述类型。