Code:
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
TSC throws the below error when I try to dispatch fetchUser() action.
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)
What generic parameters need to be passed to generic type ConfigureStoreOptions so I can pass the TSC type check.
package versions:
"@reduxjs/toolkit": "^1.5.0",
"typescript": "^4.1.2"
UPDATE
If I don't use ConfigureStoreOptions, I will get the below error when I try to set the middleware property for storeConfig dynamicly.
Property 'middleware' does not exist on type '{ reducer: { user: Reducer<{ name: string; }, AnyAction>; }; }'.ts(2339)