React Redux Toolkit中TypeScript定义带返回值Thunk函数的正确语法
在React Redux Toolkit项目中结合TypeScript开发时,若要创建一个返回布尔值的异步Thunk动作函数,你尝试的三种写法均因类型不匹配报错,核心问题在于对AppThunk泛型参数的理解偏差。
错误写法及原因
写法一
export const isAccountRemovable = (accountId: AccountId): AppThunk<boolean> => { return async (dispatch, getState) => { return false; }; };
报错信息:Type '(dispatch: ThunkDispatch<{ books: BooksState; accounts: AccountsState; transactions: TransactionsState; }, unknown, AnyAction>, getState: () => { ...; }) => Promise<...>' is not assignable to type 'AppThunk'. Type 'Promise' is not assignable to type 'boolean'.ts(2322)
原因:async函数默认返回
Promise<boolean>,但AppThunk<boolean>要求Thunk函数直接返回boolean,类型不匹配。
写法二
export const isAccountRemovable = (accountId: AccountId): AppThunk<boolean> => { return async (dispatch, getState): boolean => { return false; }; };
报错信息:The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise'?ts(1064)
原因:async函数的返回值必须是
Promise类型,不能直接声明为boolean,违反TypeScript语法规则。
写法三
export const isAccountRemovable = (accountId: AccountId): AppThunk<boolean> => { return async (dispatch, getState): Promise<boolean> => { return false; }; };
报错信息:Type '(dispatch: ThunkDispatch<{ books: BooksState; accounts: AccountsState; transactions: TransactionsState; }, unknown, AnyAction>, getState: () => { ...; }) => Promise<...>' is not assignable to type 'AppThunk'. Type 'Promise' is not assignable to type 'boolean'.ts(2322)
原因:
AppThunk<boolean>的泛型参数指定的是Thunk函数的返回类型,而这里Thunk函数返回的是Promise<boolean>,泛型参数应该改为Promise<boolean>。
正确写法
方案一:修正AppThunk泛型参数(自定义Thunk类型)
假设你的AppThunk是基于ThunkAction的类型别名,需将泛型参数指定为Promise<boolean>:
// 假设你的AppThunk定义如下 import type { ThunkAction, AnyAction } from '@reduxjs/toolkit'; import type { RootState } from '../store'; // 导入你的根状态类型 type AppThunk<ReturnType = void> = ThunkAction< ReturnType, RootState, unknown, AnyAction >; // 正确的异步Thunk函数 export const isAccountRemovable = (accountId: AccountId): AppThunk<Promise<boolean>> => { return async (dispatch, getState) => { // 这里添加你的业务逻辑,比如检查状态或发起异步请求 const state = getState(); const hasRelatedTransactions = state.transactions.some(t => t.accountId === accountId); return !hasRelatedTransactions; }; };
方案二:使用RTK官方createAsyncThunk(推荐)
Redux Toolkit的createAsyncThunk会自动处理类型推导,无需手动维护AppThunk类型:
import { createAsyncThunk } from '@reduxjs/toolkit'; import type { RootState } from '../store'; // 导入根状态类型 export const isAccountRemovable = createAsyncThunk< boolean, // 异步逻辑的返回值类型 AccountId, // 函数接收的参数类型 { state: RootState } // 额外参数类型,指定getState返回的状态类型 >( 'accounts/checkRemovable', // 动作类型前缀 async (accountId, { getState }) => { // 执行你的业务逻辑 const state = getState(); const hasRelatedTransactions = state.transactions.some(t => t.accountId === accountId); return !hasRelatedTransactions; } );
内容的提问来源于stack exchange,提问作者Sammybar

