Skip to content

自定义状态

问题

使用zustand官方提供的默认代码创建store后,ts会报错:Parameter 'newBears' implicitly has an 'any' type.

因为zustand默认的set函数没有指定类型,所以需要手动指定类型。

自定义状态

javascript
import { create } from 'zustand'

interface ICatStore {
  name: string
  age: number
  breed: string

  updateName: (newName: string) => void
  updateAge: (newAge: number) => void
  updateBreed: (newBreed: string) => void
}

export const useCatStore = create<ICatStore>()((set) => ({
  name: '',
  age: 0,
  breed: '',
  updateName: (newName: string) => set({ name: newName }),
  updateAge: (newAge: number) => set({ age: newAge }),
  updateBreed: (newBreed: string) => set({ breed: newBreed }),
}))