Sub topic 8
Typing a Store with TypeScript
This chapter assumes you can write a basic Zustand store with create, read it with selectors, and update it with set. It also assumes you know TypeScript interfaces, generics, and utility types such as Partial.
Why the Curried `create<T>()(...)` Form
Zustand's recommended TypeScript form calls create twice:
import { create } from 'zustand'
interface TodoState {
todos: string[]
filter: 'all' | 'open'
addTodo: (title: string) => void
setFilter: (filter: TodoState['filter']) => void
}
export const useTodoStore = create<TodoState>()((set) => ({
todos: [],
filter: 'all',
addTodo: (title) => set((state) => ({ todos: [...state.todos, title] })),
setFilter: (filter) => set({ filter }),
}))TypeScript cannot infer some generic parameters while you supply others explicitly. The first call, create<TodoState>(), fixes the state type. The second call receives the state creator and infers the remaining types, which include the middleware types. Without this split, you would have to write out every generic by hand.
For a plain store with no middleware, create<TodoState>(creator) also compiles. Once you add middleware, inference tends to break with that form, so use the curried form everywhere.
The store type is the single source of truth. It lists both data and actions, so the creator function must return every field. If you forget setFilter, TypeScript reports the missing property at the object literal.
What `set` Accepts
set is typed to take either a partial state or a function that returns one:
set({ filter: 'open' })mergesfilterinto the state.set((state) => ({ todos: [...state.todos, 'x'] }))computes the partial from the current state.
Because the partial is checked against TodoState, these calls fail to compile:
useTodoStore.setState({ filter: 'done' }) // 'done' is not 'all' | 'open'
useTodoStore.setState({ counter: 1 }) // 'counter' does not exist on TodoStateSince the partial is checked against Partial<TodoState>, you can omit fields but you cannot invent them. That catches typos in field names.
A second argument, true, replaces the state instead of merging it. In that mode, TypeScript requires the full state object, so you cannot accidentally drop fields.
Typing Selectors
You rarely annotate selectors. The hook is generic over the selector's return type, so inference does the work:
const count = useTodoStore((state) => state.todos.length) // number
const filter = useTodoStore((state) => state.filter) // 'all' | 'open'
const addTodo = useTodoStore((state) => state.addTodo) // (title: string) => voidThe state parameter is TodoState, so autocomplete works and renames propagate. If you write a reusable selector outside a component, type its parameter:
const selectOpenCount = (state: TodoState) => state.todos.lengthYou can then call useTodoStore(selectOpenCount).
Getting the State Type Back Out
You may need the state type in a helper or a test when you did not export the interface. Derive it from the store:
type TodoSnapshot = ReturnType<typeof useTodoStore.getState>This stays correct as the interface changes. Exporting the interface is also fine. Prefer one approach per codebase.
Typing with Middleware
Middleware wraps the creator, and each wrapper adds to the store's types. With the curried form, the inner set is still contextually typed:
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
interface SettingsState {
theme: 'light' | 'dark'
token: string | null
setTheme: (theme: SettingsState['theme']) => void
setToken: (token: string | null) => void
}
export const useSettingsStore = create<SettingsState>()(
devtools(
persist(
(set) => ({
theme: 'light',
token: null,
setTheme: (theme) => set({ theme }),
setToken: (token) => set({ token }),
}),
{
name: 'settings',
partialize: (state) => ({ theme: state.theme }),
},
),
{ name: 'SettingsStore' },
),
)Three points about this example:
set,theme, andtokenare all typed without annotations, becausecreate<SettingsState>()supplies the state type to the whole middleware chain.partializereceives the fullSettingsStateand returns a smaller object. The hook's state type does not change. Only the persisted shape is narrower.- Middleware also adds methods to the store. After
persist,useSettingsStore.persist.clearStorage()is typed and available.
Typing Slices
Slices are where typing gets harder, because a slice must know about the whole store but only returns its own part. StateCreator takes four type parameters:
StateCreator<FullState, MiddlewaresIn, MiddlewaresOut, SliceReturn>| Parameter | Meaning |
|---|---|
| `FullState` | The combined state that `set` and `get` operate on. |
| `MiddlewaresIn` | Middleware that wraps this slice from outside, which changes the type of `set`. |
| `MiddlewaresOut` | Middleware this slice itself applies. Usually `[]`. |
| `SliceReturn` | The part of the state this slice returns. |
Without middleware, both middleware lists are []:
import { create, StateCreator } from 'zustand'
interface BearSlice {
bears: number
addBear: () => void
}
interface FishSlice {
fishes: number
addFish: () => void
addBoth: () => void
}
type AllSlices = BearSlice & FishSlice
const createBearSlice: StateCreator<AllSlices, [], [], BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
})
const createFishSlice: StateCreator<AllSlices, [], [], FishSlice> = (set, get) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
addBoth: () => {
get().addBear()
get().addFish()
},
})
export const useBoundStore = create<AllSlices>()((...args) => ({
...createBearSlice(...args),
...createFishSlice(...args),
}))FishSlice.addBoth calls get().addBear(), which only type-checks because the first parameter is AllSlices and not FishSlice.
When the store is wrapped in middleware, each slice must declare it. Here the whole store uses devtools:
import { create, StateCreator } from 'zustand'
import { devtools } from 'zustand/middleware'
interface BearSlice {
bears: number
addBear: () => void
}
interface FishSlice {
fishes: number
addFish: () => void
}
type AllSlices = BearSlice & FishSlice
const createBearSlice: StateCreator<
AllSlices,
[['zustand/devtools', never]],
[],
BearSlice
> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/add'),
})
const createFishSlice: StateCreator<
AllSlices,
[['zustand/devtools', never]],
[],
FishSlice
> = (set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/add'),
})
export const useBoundStore = create<AllSlices>()(
devtools((...args) => ({
...createBearSlice(...args),
...createFishSlice(...args),
})),
)The [['zustand/devtools', never]] entry tells TypeScript that set accepts devtools' extra arguments: a replace flag and an action name. If you leave it out, the set call with three arguments fails to compile.
Common Typing Errors
- Forgetting the second call.
create<T>()alone returns a function, not a hook. CallinguseStore()then fails. - Declaring actions outside the interface. The creator returns extra properties that TypeScript rejects as excess, or components cannot see them.
- Mismatched slice middleware. If the store uses
devtoolsand a slice declares[], the slice'ssettype does not match what the store passes in. - Annotating the selector return. Writing
(state): number => ...is harmless but redundant. Over-annotating can hide a wrong type behind a wider one. - Optional fields for loading state. Prefer
user: User | nulloveruser?: User. Thenullmakes the "not loaded" state explicit, andset({ user: null })is a valid reset.
Exercise
A store is created with create<CartState>()(devtools((set) => ({ ... }))). A teammate calls set({ items: [] }, false, 'cart/clear') inside an action and gets a type error in a slice file declared as StateCreator<CartState, [], [], CartSlice>. What is wrong, and how do you fix it?
Show answer
The slice declares no incoming middleware, so its set only accepts one or two arguments and does not know about the action-name parameter that devtools adds. Change the second type parameter to [['zustand/devtools', never]], so the slice type is StateCreator<CartState, [['zustand/devtools', never]], [], CartSlice>.
Exercise
Given useTodoStore from this chapter, write a type alias TodoFilter that always matches the filter field's type, without repeating the literal union.
Show answer
type TodoFilter = ReturnType<typeof useTodoStore.getState>['filter']. You can also write TodoState['filter'] if the interface is exported. Either form updates automatically when the union changes.