this is my app store in react redux when using typescript:
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from '../reducer/combineReducer';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
const logger = createLogger();
const initialState = {
};
const store = configureStore({
reducer: rootReducer,
middleware: [logger, thunk],
devTools: process.env.NODE_ENV !== 'production',
preloadedState: initialState
});
export default store;
now I want to give some initial global data structure in preloadedState, then I tweak the initialState code like this:
const initialState = {
user: {}
};
the visual studio code shows error:
Type '{ user: {}; }' is not assignable to type '{ readonly [$CombinedState]?: undefined; user?: { user: any; loginUser: {}; } | { loginUser: any; user: {}; } | undefined; }'.
Types of property 'user' are incompatible.
Type '{}' is not assignable to type '{ user: any; loginUser: {}; } | { loginUser: any; user: {}; } | undefined'.ts(2322)
configureStore.d.ts(45, 5): The expected type comes from property 'preloadedState' which is declared here on type 'ConfigureStoreOptions<CombinedState<{ user: { user: any; loginUser: {}; } | { loginUser: any; user: {}; }; }>, any, Middleware<{}, any, Dispatch<AnyAction>>[], [...]>'
(property) ConfigureStoreOptions<CombinedState<{ user: { user: any; loginUser: {}; } | { loginUser: any; user: {}; }; }>, any, Middleware<{}, any, Dispatch<AnyAction>>[], [...]>.preloadedState?: {
readonly [$CombinedState]?: undefined;
user?: {
user: any;
loginUser: {};
} | {
loginUser: any;
user: {};
} | undefined;
} | undefined
what should I do to add some initial global field define?
The answer lies in the error message:
Type '{}' is not assignable to type '{ user: any; loginUser: {}; } | { loginUser: any; user: {}; } | undefined'
TypeScript expects the value of user
to be an object with user
and loginUser
fields, but you are giving an empty object instead. Pass these in the object to fix the error.
The type definition of ConfigureStoreOptions
also explains this:
/**
* The initial state, same as Redux's createStore.
* You may optionally specify it to hydrate the state
* from the server in universal apps, or to restore a previously serialized
* user session. If you use `combineReducers()` to produce the root reducer
* function (either directly or indirectly by passing an object as `reducer`),
* this must be an object with the same shape as the reducer map keys.
*/
preloadedState?: DeepPartial<S extends any ? S : S>