【问题标题】:ThunkAction getting returned by dispatch instead of the Return Type of the ThunkAction通过调度返回 ThunkAction 而不是 ThunkAction 的返回类型
【发布时间】:2020-11-11 11:20:32
【问题描述】:

如何将 Typescript 配置为与 react-redux 和 redux-thunk 一起使用,以便 dispatch 返回被调度的 ThunkAction 的返回类型,而不是 ThunkAction<a,b,c,d,e>

export function addPerson(
  person: Person
): PersonActionTypes {
  return {
    type: ADD_PERSON,
    person,
  }
}


export const savePerson = (
  person: Person
): ThunkAction<
  Promise<Person>,
  RootState,
  unknown,
  Action<string>
> => async (dispatch): Promise<Person> => {
  const savedPerson = await PersonApi.save(person)
  dispatch(addPerson(savedPerson))
  return savedPerson
}

当我调度这个动作时,我希望它返回一个Promise&lt;Person&gt;,但调度返回ThunkAction&lt;Promise&lt;void&gt;, RootState, unknown, Action&lt;string&gt;&gt;

const savedPerson = await dispatch(savePerson(person))
// savedPerson is a ThunkAction as far as TypeScript is concerned but I would like it to be a Person.

【问题讨论】:

  • 如果你这样做了const savedPerson = await savePerson(person)(dispatch)

标签: reactjs typescript react-redux


【解决方案1】:

面临同样的问题。一段时间后找到了一个对我有用的解决方案。 这里的问题是dispatch 默认获取类型Dispatch 并且对于简单的操作是可以的,但不适用于ThunkAction

我的 thunk 动作是这样描述的:

type AppThunk<ReturnType = void> = ThunkAction<ReturnType, StateType, unknown, Action<string>>;
export const thunkAction = (id: number): AppThunk<Promise<{ status: string }>> => async (dispatch) => { ...do something, return correct type };

我已经为我的 thunk-dispatch 创建了类型

export type AppThunkDispatch = ThunkDispatch<StateType, unknown, Action<string>>;

之后我就可以使用返回值而不会出现类型错误,如下所示:

const data  = await (dispatch as AppThunkDispatch)(thunkAction(33));
if (data.status === 'success') { console.log('perfect') }

如果你在这个特定组件中只有 thunk 动作要调度,认为你可以定义一次调度类型

const dispatch: AppThunkDispatch = useDispatch();

并避免(dispatch as AppThunkDispatch) 强制转换

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 2021-02-27
    • 2021-02-11
    • 2020-05-19
    • 2022-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多