I want to get a type for redux state, which will be used to mock said state.
So far I figured out I have this Reducer:
(alias) const reducer: {
selectedElement: Reducer<StructureElement, AnyAction>;
fetchedState: Reducer<FetchedState, AnyAction>;
... 10 more ...;
mesApi: Reducer<...>;
}
So what I want to do, is somehow get the StructureElement
, FetchedState
and so on from inside of the Reducer</here/, AnyAction>;
part.
How can I achieve that?
Or is there a better way to get combined state type? It has to be done automatically though. I don't want to change types in 2 places when it should be auto-generated.
If I try this:
type State = typeof reducer;
I get
Type '{ selectedElement: Reducer<StructureElement, AnyAction>; fetchedState: Reducer<FetchedState, AnyAction>; ... 10 more ...; mesApi: Reducer<...>; }' is not assignable to type '{ selectedElement?: { stateId: string; parentId: string; hasChild: boolean; pathList: string[]; name: string; color: string; isActive: boolean; level: number; children?: ...[]; key?: string; type: StateType; }; ... 11 more ...; mesApi?: { ...; }; }'. Types of property 'selectedElement' are incompatible.
which makes sense.
CodePudding user response:
I'd recommend to simply model it explicitly and then import those types where you need them:
export type UserState = {
readonly isLoggedIn: boolean;
// other user state here
};
// Type for entire global redux state
export type AppState = {
users: UserState;
// other sub-states here
};
CodePudding user response:
I personally create a slice for each feature that I want in my state, then I have a file in which I'll first declare and export my RootState Type, and then I'll combine all of my reducers.
export interface RootState {
pokemon: pokemonState;
pokemonTrainer: pokemonTrainerState;
}
const reducer = combineReducers<RootState>({
pokemon: pokemonSLice,
pokemonTrainer: pokemonTrainerSlice,
});
Where pokemonState
and pokemonTrainerState
are the types of each feature.
And then I'll use RootState
wherever I need.