如何配置 Typescript 与 React-Redux 和 Redux-thunk 一起使用,以便 dispatch
返回正在分派(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<Person>
但调度返回 ThunkAction<Promise<void>, RootState, unknown, Action<string>>
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.
最佳答案
遇到同样的问题。一段时间后找到了一个对我有用的解决方案。
这里的问题是,dispatch
默认情况下获取类型 Dispatch
,并且对于简单操作来说是可以的,但对于 ThunkAction
则不行。
我的 thunk Action 是这样描述的:
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 操作要分派(dispatch),那么您可以定义一次分派(dispatch)类型
const dispatch: AppThunkDispatch = useDispatch();
并避免(作为 AppThunkDispatch 调度)
转换
关于reactjs - ThunkAction 通过调度返回,而不是 ThunkAction 的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63025338/