Sub topic 8
Typing a Store with TypeScript
This chapter assumes you know basic TypeScript (interfaces, generics) and have created a Zustand store with create. Here you will type a store correctly and see why the syntax has an extra pair of parentheses.
Describe the state in one interface
Zustand infers nothing about your state shape on its own. You write one interface that holds both the data and the actions, then pass it to create.
import { create } from 'zustand'
interface CounterState {
count: number
increment: () => void
reset: () => void
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}))With this interface, set knows its argument is a Partial<CounterState> or a function returning one. A typo such as set({ cuont: 0 }) is a compile error. Selectors are typed too, so useCounterStore((s) => s.count) returns number.
Why `create<T>()(...)`
The form create<CounterState>()((set) => ...) has two calls. The first call, create<CounterState>(), fixes the state type. The second call receives the state creator function.
TypeScript cannot partly infer generics. If you wrote create<CounterState>((set) => ...), the compiler would have to accept your type and also infer the middleware types, and it cannot do both in one call. Splitting the call lets you supply the state type by hand while the middleware types are inferred in the second call.
Using `get` and middleware
The state creator also receives get, which returns the current state. It is typed from the same interface.
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
interface CartState {
items: string[]
addItem: (item: string) => void
logCount: () => void
}
export const useCartStore = create<CartState>()(
devtools((set, get) => ({
items: [],
addItem: (item) => set((state) => ({ items: [...state.items, item] })),
logCount: () => console.log(get().items.length),
})),
)Because of the curried form, devtools composes without extra type annotations. Inside the creator, item is inferred as string from the interface.
Typing slices
When a store is split into slices, each slice is typed with StateCreator. Its four generic arguments are the full store type, the middleware applied before this slice, the middleware applied after it, and the slice's own type. For a store without middleware you pass empty tuples:
import { StateCreator } from 'zustand'
interface BearSlice {
bears: number
addBear: () => void
}
interface FishSlice {
fishes: number
}
type AllSlices = BearSlice & FishSlice
const createBearSlice: StateCreator<AllSlices, [], [], BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
})Typing the first argument as AllSlices lets a slice read and update state owned by other slices.
Common errors
- Writing
create<T>(...)without the second call. Middleware types then fail to infer. - Putting the action types outside the interface. Actions belong in the state type so selectors can return them.
- Using
anyfor the state creator argument. You lose checking onsetandget.
Exercise
Why does Zustand's TypeScript form use create<State>()(creator) instead of create<State>(creator)?
Show answer
TypeScript cannot supply some generic arguments by hand and infer the rest in a single call. The first call fixes the state type, and the second call lets the compiler infer the middleware types from the creator.