Summary: Can all actions with their payloads be automatically grouped by sub-store in a composite store using a single type entity (e.g., interface
)?
I have implemented a Redux store with multiple sub-stores structured as follows:
- There is an action
that updatessetAppLoading(isLoading :boolean)
state.app.loading
with the provided payload; - Another action
setUserName(name: string | null)
also updatesstate.user.name
depending on the passed payload (which can be nullable if user doesn't exist); - Additionally, there is an action
logOut()
which performs some API tasks and then callssetUserName(null)
internally;
The desired outcome is to infer the complete structure of the store like so:
interface ActionsMap {
app: {
setAppLoading(isLoading: boolean): void
}
user: {
setUserName(name: string | null): void
logOut(): void
}
}
Is it feasible to derive this type from existing entities (as shown below)? The goal is to define everything once without the need to re-export, especially since there may be instances where an action is created but not referenced elsewhere.
An instance of the store
has already been configured using configureStore()
and combineReducers()
, providing proper typing. Sub-store names can be inferred from it as well:
type State = ReturnType<typeof store.getState>
// excluding internal key `typeof $CombinedState`
type SubStoreName = Extract<keyof State, string>
Each store already has a collection of related actions with correct typings:
import * as appActions from 'store/app/actions'
import * as userActions from 'store/user/actions'
dispatch(appActions.setAppLoading(true))
dispatch(userActions.logOut())
One approach I've considered involves utilizing this setup:
const actionsMap = {
app: appActions,
game: gameActions,
} satisfies Record<SubStoreName, unknown>
type ActionsMap = typeof actionsMap
This method would require me to "re-export" items, even though it serves as a reminder to export everything when necessary.