Zustand v4+ dùng curried create: create<StoreType>()((set, get) => ({ ... })) — thiếu cặp () thứ hai thì TypeScript không infer đúng.
Định nghĩa type cho toàn bộ store trước, rồi truyền vào generic.
ts
interface CartStore {
items: CartItem[]
total: number
addItem: (item: CartItem) => void
clearCart: () => void
}
const useCartStore = create<CartStore>()((set, get) => ({
items: [],
total: 0,
addItem: (item) => set((s) => ({
items: [...s.items, item],
total: s.total + item.price,
})),
clearCart: () => set({ items: [], total: 0 }),
}))Với slice thì dùng type StateCreator:
ts
type CartSlice = { items: CartItem[]; addItem: (item: CartItem) => void }
const createCartSlice: StateCreator<BoundStore, [], [], CartSlice> = (set) => ({
items: [],
addItem: (item) => set((s) => ({ items: [...s.items, item] })),
})Suy ngược type của store từ chính store:
type StoreState = ReturnType<typeof useStore.getState>Lưu ý: đừng dùng create mà bỏ generic — mất type safety và set nhận any.