在 Zustand 中使用 TypeScript 的方法:
- 基本类型定义:
import { create } from 'zustand';
// 定义状态和动作的类型
interface StoreState {
// 状态
count: number;
user: {
id: string;
name: string;
email: string;
} | null;
// 动作
increment: () => void;
decrement: () => void;
setUser: (user: StoreState['user']) => void;
reset: () => void;
}
// 创建带类型的 store
const useStore = create<StoreState>((set) => ({
// 状态
count: 0,
user: null,
// 动作
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
setUser: (user) => set({ user }),
reset: () => set({ count: 0, user: null }),
}));
- 使用 get 的类型定义:
import { create } from 'zustand';
interface StoreState {
count: number;
user: {
id: string;
name: string;
} | null;
increment: () => void;
incrementBy: (value: number) => void;
fetchUser: (userId: string) => Promise<void>;
}
const useStore = create<StoreState>((set, get) => ({
count: 0,
user: null,
increment: () => set((state) => ({ count: state.count + 1 })),
incrementBy: (value) => set((state) => ({ count: state.count + value })),
// 使用 get 获取最新状态
fetchUser: async (userId) => {
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
set({ user: userData });
// 使用 get 获取最新状态
console.log('Current count:', get().count);
} catch (error) {
console.error('Error fetching user:', error);
}
},
}));
- 使用中间件时的类型定义:
import { create } from 'zustand';
import { persist, PersistOptions } from 'zustand/middleware';
interface StoreState {
count: number;
user: {
id: string;
name: string;
} | null;
increment: () => void;
setUser: (user: StoreState['user']) => void;
}
// 定义 persist 中间件的类型
type StorePersist = {
persist: {
clearStorage: () => void;
};
};
// 完整的 store 类型
type Store = StoreState & StorePersist;
// persist 配置类型
type PersistConfig = PersistOptions<StoreState, StorePersist>;
const useStore = create<Store>(
persist<StoreState, StorePersist>(
(set) => ({
count: 0,
user: null,
increment: () => set((state) => ({ count: state.count + 1 })),
setUser: (user) => set({ user }),
}),
{
name: 'my-storage',
} as PersistConfig
)
);
- 使用 selectors 的类型定义:
import { create } from 'zustand';
import { StoreState } from './store';
// 在组件中使用
function Counter() {
// 类型安全的 selector
const count = useStore((state: StoreState) => state.count);
const increment = useStore((state: StoreState) => state.increment);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
}
关键点:
- 使用 TypeScript 接口定义状态和动作的类型
- 在 create 函数中指定泛型类型
- 为 get 和 set 函数提供正确的类型
- 在使用中间件时,需要正确定义中间件的类型
- 确保 selector 函数的返回类型与使用场景匹配
- TypeScript 可以帮助捕获状态更新和使用中的类型错误