代码:
import { configureStore, ConfigureStoreOptions, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import logger from 'redux-logger';
interface fetchUserResponse {
name: string;
}
const fetchUser = createAsyncThunk<fetchUserResponse, void>('users/fetchUser', async () => {
return { name: 'teresa teng' };
});
const usersSlice = createSlice({
name: 'users',
initialState: { name: '' },
reducers: {},
extraReducers: (builder) => {
builder.addCase(fetchUser.fulfilled, (state, action) => {
state.name = action.payload.name;
});
},
});
interface UserState {
name: string;
}
interface AppState {
user: UserState;
}
const storeConfig: ConfigureStoreOptions<AppState> = {
reducer: {
user: usersSlice.reducer,
},
};
if (process.env.NODE_ENV !== 'production') {
storeConfig.middleware = (getDefaultMiddlewares) => getDefaultMiddlewares().concat(logger);
}
const store = configureStore(storeConfig);
store.dispatch(fetchUser()); // TSC throws error
当我尝试分派(dispatch) fetchUser()
操作时,TSC 抛出以下错误。
Argument of type 'AsyncThunkAction<fetchUserResponse, void, {}>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type 'AsyncThunkAction<fetchUserResponse, void, {}>' but required in type 'AnyAction'.ts(2345)
需要将哪些泛型参数传递给泛型类型 ConfigureStoreOptions
,以便我可以通过 TSC 类型检查。
软件包版本:
"@reduxjs/toolkit": "^1.5.0",
"typescript": "^4.1.2"
更新
如果我不使用 ConfigureStoreOptions
,当我尝试动态设置 storeConfig
的 middleware
属性时,我会收到以下错误。
Property 'middleware' does not exist on type '{ reducer: { user: Reducer<{ name: string; }, AnyAction>; }; }'.ts(2339)
最佳答案
正如@phry所说,您可以跳过 ConfigureStoreOptions
的使用如果您只是调用configureStore
,请完整键入直接:
const store = configureStore({
reducer: {
user: usersSlice.reducer
}
});
您的 storeConfig: ConfigureStoreOptions<AppState>
中缺少的部分type 是中间件类型的声明。当前类型不包含 thunk 或任何其他中间件,因此您无法调度 AsyncThunkAction
。您需要调整您的 storeConfig
键入以支持 thunks。您可以通过设置第三个泛型类型参数 M
来完成此操作。 .
以下是类型的定义方式:
ConfigureStoreOptions<S = any, A extends Action<any> = AnyAction, M extends Middlewares<S> = Middlewares<S>>
您需要导入 ThunkMiddleware
直接从“redux-thunk”输入,因为“@reduxjs/toolkit”不会重新导出它。
import { configureStore, ConfigureStoreOptions } from "@reduxjs/toolkit";
import {ThunkMiddleware} from "redux-thunk";
const storeConfig: ConfigureStoreOptions<AppState, AnyAction, [ThunkMiddleware<AppState, AnyAction>]> = {
reducer: {
user: usersSlice.reducer
}
};
const store = configureStore(storeConfig);
store.dispatch(fetchUser());
你可以这样做并且它有效,但是当你可以直接将你的选项传递给 configureStore
时,这真的很愚蠢。并推断出所有类型。
关于typescript - 类型 'type' 中缺少属性 'AsyncThunkAction<fetchUserResponse, void, {}>',但类型 'AnyAction' 中需要属性 0x104567910,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67108054/