|
When using Zustand the “classic way”, we often define an interface for the store: interface BearState {
bears: number
increase: (by: number) => void
}
const useBearStore = create<BearState>()((set) => ({
bears: 0,
increase: (by) => set((state) => ({ bears: state.bears + by })),
}))But as the store grows and more actions are added, keeping this interface updated becomes annoying. Every time you add or rename an action, you must update the interface too — lots of extra typing and duplication. So I switched to this cleaner pattern 👇 const initialState = { bears: 0 }
export type BearState = typeof initialState
export const useBearStore = create<BearState>()(() => initialState)
export const bearActions = {
increase(by: number) {
useBearStore.setState((state) => ({ bears: state.bears + by }))
},
}✨ Why it’s better
|
Answered by
suhaotian
Oct 8, 2025
Replies: 1 comment
|
What if the fields in const initialState = {
bears: 0,
gender: 1 as 0 | 1 | 2 | undefined,
};
export type BearState = typeof initialState; |
0 replies
Answer selected by
suhaotian
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if the fields in
initialStatearenull,undefined,uniontypes, orstring? We can use TypeScript’sassyntax to fix this issue and avoid rewriting the store’s type. For example: