useReducer的initialState键入为永不?

时间:2019-02-19 16:37:32

标签: reactjs typescript

initialState出现错误:类型'{{email:string;密码:字符串;有效:布尔值; }”不能分配给“ never”类型的参数。ts(2345)


function reducer(state: IState, action: IFluxAction) {
  const Users = UsersFetch()
  switch (action.type) {
    case 'email':
      const email = action.value
      const valid = Users.find(e => e === email) ? true : false

      return {
        email,
        valid,
      }
    case 'password':
      const password = action.value
      return {
        password,
      }
    default:
      throw new Error()
  }
}
  const initialState = {
    email: '',
    password: '',
    valid: false,
  }
  const [state, dispatch] = React.useReducer(reducer, initialState)

键入此错误以满足错误的正确方法是什么?

反应16.8.1 Typescript 3.3.1

应该(由其固定)...state添加到退货中,例如

  switch (action.type) {
    case 'email':
      const email = action.value
      const valid = Users.find(e => e === email) ? true : false

      return {
        ...state,
        email,
        valid,
      }
    case 'password':
      const password = action.value
      return {
        ...state,
        password,
      }
    default:
      throw new Error()
  }

此外-正如@madflanderz所建议的那样,将IState设置为reducer的预期返回值有助于解决此类问题。

2 个答案:

答案 0 :(得分:4)

我也在这个问题上挣扎。在我看来,预防错误的最佳方法似乎是将State Interface添加为reducer的返回类型。然后,您可以在化简器内看到类型错误,而不是在useReducer行上。

像这样:

function reducer(state: IState, action: IFluxAction): IState {
   // reducer code
   // type errors are visible here 
}

答案 1 :(得分:1)

问题很可能与您的减速器声明有关。 initialState的类型必须与reducer函数中的状态类型和返回值相同。

这将起作用:

function reducer(state: {email: string}) {
  return state
}
const initialState = {
  email: '',
}
const [state, dispatch] = React.useReducer(reducer, initialState)

这将产生一个错误:

// state has a different type than initialState.
function reducer(state: {address: string}) {
  // No return statement.
}
const initialState = {
  email: '',
}
const [state, dispatch] = React.useReducer(reducer, initialState) // Error

在React的键入you can see中,useReducer泛型函数始终期望initialState类型为ReducerState<R>类型。 The ReducerState<R>是一个conditional type,它试图推断正确的状态类型,如果失败则退回到never