You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Zustand中使用TypeScript时,store的set函数类型报错如何解决?

解决方案

你可以使用zustand内置的SetState类型来为set函数指定类型,无需使用any。具体步骤如下:

  1. 首先从zustand导入SetState类型
  2. 确保你已经正确定义了TemplateStore接口,包含所有状态和方法
  3. 将set的类型从any替换为SetState<TemplateStore>

完整代码示例

1. 定义接口并导入类型

import { SetState, create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

// 定义完整的Store接口
interface TemplateStore {
  borderRadius: number;
  drawerWidth: number;
  fontFamily: string;
  headerHeight: number;
  language: string;
  opened: boolean;
  setLang: (lang: string) => void;
  setMenu: () => void;
}

2. 修正Store函数的类型

const templateStore = (set: SetState<TemplateStore>) => ({
  borderRadius: 12,
  drawerWidth: 250,
  fontFamily: `'Roboto', sans-serif`, // 注意:你原代码此处多了一个多余的单引号,已修正
  headerHeight: 80,
  language: 'UK',
  opened: true,
  setLang: (lang: string) => set({ language: lang }),
  setMenu: () => set((state) => ({ opened: !state.opened })), // state类型会自动推导为TemplateStore,无需手动指定
});

3. Hook部分保持不变

const useTemplateStore = create<TemplateStore>()(
  devtools(
    persist(templateStore, {
      name: 'template',
    }),
  ),
);

说明

SetState<T>是zustand提供的内置通用类型,它准确描述了set函数的两种调用方式:

  • 直接传入部分状态对象进行更新
  • 传入接收当前状态的回调函数,返回新的状态片段

这样既满足TypeScript的类型校验,又避免了使用any带来的类型不安全问题。

内容的提问来源于stack exchange,提问作者CzechCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 17:47:24