如何理解redux-thunk中TypeScript ThunkAction的泛型及API用法?
ThunkAction 泛型参数说明
redux-thunk 内置的ThunkAction类型的完整泛型签名为:
ThunkAction<ReturnType, State, ExtraThunkArg, BasicAction>
四个泛型参数的实际作用如下:
- ReturnType:thunk函数(即action creator返回的、会被thunk中间件执行的嵌套函数)本身的返回值类型,与最终派发给reducer的普通action类型无直接关联。API请求类的thunk返回值通常是带业务结果的Promise,类型标注为
Promise<业务返回值类型>即可;如果thunk执行完无返回值,标注为void。 - State:项目Redux Store的根状态类型。thunk执行时可以通过注入的
getState方法读取全局状态,该参数为getState的返回值提供类型约束,避免取值时出现类型错误。 - ExtraThunkArg:初始化thunk中间件时,通过
thunk.withExtraArgument()注入的自定义额外参数的类型。未配置自定义额外参数时,直接填undefined。 - BasicAction:约束thunk执行过程中派发给reducer的普通action的类型范围,一般填写项目中所有合法可派发action的联合类型;不需要严格做action类型校验时,可直接使用Redux自带的
AnyAction类型。
API请求场景的正确使用示例
前置类型定义
// 全局根状态类型,作为ThunkAction的第二个泛型参数 interface RootState { userInfo: { id: number; name: string; }; loading: boolean; } // 项目中所有合法可派发的普通action联合类型,作为ThunkAction的第四个泛型参数 type AppDispatchActions = | { type: 'user/set_loading'; payload: boolean } | { type: 'user/set_user_info'; payload: RootState['userInfo'] };
具体thunk实现
import { ThunkAction } from 'redux-thunk'; // 发起用户信息API请求的thunk function fetchUserProfile(userId: number): ThunkAction<Promise<number>, RootState, undefined, AppDispatchActions> { // 泛型对应关系: // 1. ReturnType: 请求成功后返回获取到的用户id,类型为Promise<number> // 2. State: 全局根状态类型RootState // 3. ExtraThunkArg: 无自定义注入参数,填undefined // 4. BasicAction: 约束内部派发的action必须属于AppDispatchActions联合类型 return async (dispatch, getState) => { // 读取全局状态时可获得完整类型提示 const isLoading = getState().loading; if (isLoading) return 0; // 派发符合类型约束的普通action dispatch({ type: 'user/set_loading', payload: true }); try { const response = await fetch(`/api/user/${userId}`).then(res => res.json()); dispatch({ type: 'user/set_user_info', payload: response.data }); // 该返回值匹配第一个泛型定义的Promise<number> return response.data.id; } catch (err) { return 0; } finally { dispatch({ type: 'user/set_loading', payload: false }); } }; }
常见使用注意事项
- 不要将第一个泛型参数混淆为派发给reducer的action类型,前者是thunk函数自身的返回值,后者是第四个泛型的约束范围
- 未配置自定义thunk额外参数时,第三个泛型不要随意填写
unknown或其他自定义类型,否则会导致thunk内读取注入参数时出现类型不匹配报错 - 不需要严格action类型校验的项目,可直接将第四个泛型替换为
AnyAction,减少重复维护action联合类型的成本
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

