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

TypeScript中如何向Zustand的create调用传递泛型接口?

泛型Zustand Store的正确实现与调用语法

你的代码存在两个核心问题:一是定义itemStore时,create<Item<T>>()中的T未被声明,TypeScript无法识别这个泛型参数;二是你期望的itemStore<T>(state => state.data)调用方式,需要让store本身支持泛型参数传递,或者通过泛型函数来创建不同类型的store实例。

下面给出两种常用的正确实现方案:

方案一:通过泛型函数创建特定类型的Store

这种方式适合需要提前确定data类型的场景,创建store时就指定泛型参数,后续调用选择器时自动推导类型:

import { create } from "zustand";

interface Item<T> {
  count: number;
  data: T;
  // 可选:添加修改数据的方法
  setData: (newData: T) => void;
}

// 封装一个泛型函数,用于创建指定类型的Item Store
function createItemStore<T>(initialData: T) {
  return create<Item<T>>((set) => ({
    count: 1,
    data: initialData,
    setData: (newData) => set({ data: newData })
  }));
}

// 创建一个存储字符串类型data的store
const itemStore = createItemStore<string>("generic");

// 调用选择器获取data,此时data的类型自动推导为string
const data = itemStore(state => state.data);

方案二:动态指定泛型类型调用选择器

如果需要在调用选择器时才确定data的类型,可以将store的泛型参数设为默认值(比如unknown),调用时通过泛型参数约束返回类型:

import { create } from "zustand";

// 给泛型参数设置默认值unknown,让store更灵活
interface Item<T = unknown> {
  count: number;
  data: T;
}

// 创建store时使用默认泛型类型
const itemStore = create<Item>()((set) => ({
  count: 1,
  data: "generic" as unknown // 初始值需要断言为unknown以适配泛型
}));

// 调用时通过泛型参数指定Item的类型,从而确定data的类型
const data = itemStore<Item<string>>(state => state.data);
// 或者直接断言返回值的类型(更简洁)
const data = itemStore(state => state.data) as string;

关键要点

  • 泛型参数必须在被使用前声明:要么在函数/接口定义时声明,要么在调用时显式指定。
  • Zustand的store本身是一个接受选择器的函数,若要让它支持泛型参数,要么通过泛型工厂函数创建store,要么在调用选择器时通过泛型约束返回类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:05:21