属性 'type' 在类型 'AsyncThunkAction<fetchUserResponse, void, {}>' 中缺失,但在类型 'AnyAction' 中是必需的



代码:

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

当我尝试调度fetchUser()操作时,TSC 会抛出以下错误。

类型为"AsyncThunkAction<fetchUserResponse,>"的参数不能分配给类型为"AnyAction"的参数。 类型"AsyncThunkAction<fetchUserResponse,>"中缺少属性"type",但在类型"AnyAction"中是必需的.ts(2345)

需要将哪些泛型参数传递给泛型类型ConfigureStoreOptions以便我可以通过 TSC 类型检查。

软件包版本:

"@reduxjs/toolkit": "^1.5.0",
"typescript": "^4.1.2"

更新

如果我不使用ConfigureStoreOptions,当我尝试动态设置storeConfigmiddleware属性时,会出现以下错误。

属性"中间件"在类型"{ reducer: { user: Reducer<{ name: string; }, AnyAction>; }; }' 上不存在。TS(2339)

正如@phry所说,如果你直接调用configureStore,你可以完全跳过ConfigureStoreOptions类型的使用:

const store = configureStore({
reducer: {
user: usersSlice.reducer
}
});

storeConfig: ConfigureStoreOptions<AppState>类型中缺少的部分是中间件类型的声明。 当前类型不包括 thunk 或任何其他中间件,因此您无法调度AsyncThunkAction。 您需要调整storeConfig类型以支持 thunks。 为此,请将第三个泛型类型参数设置为M

以下是定义类型的方式:

ConfigureStoreOptions<S = any, A extends Action<any> = AnyAction, M extends Middlewares<S> = Middlewares<S>>

您需要直接从"redux-thunk"导入ThunkMiddleware类型,因为"@reduxjs/工具包"不会重新导出它。

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并推断出所有类型时,这很愚蠢。

Redux-toolkit 维护者

在这里ConfigureStoreOptions真的不是一种你应该手动使用的类型 - 它意味着通过实际调用configureStore来推断。(我真的不知道如何手动输入它,我已经完成了当前 RTK 类型的大部分工作)

这实际上是我第一次看到有人这样做。有什么紧迫的原因让你真的必须这样做吗?也许我可以提供一个替代方案。

看到您更新的代码后,我真的建议您做类似的事情

const store = configureStore({
reducer: {
user: usersSlice.reducer,
},
middleware(getDefaultMiddlewares) {
if (process.env.NODE_ENV !== 'production') {
return getDefaultMiddlewares().concat(logger);
}
else {
return getDefaultMiddlewares()
}
}
});

你可以看到它在这个操场上工作

遇到了同样的问题,我不得不middleware: [thunk as ThunkMiddleware]添加到我的configureStore()中才能获得createAsyncThunk()的正确类型

相关内容