React项目中使用Zustand Persist中间件遇TypeScript类型错误
解决Zustand persist中间件的TypeScript类型不兼容错误
错误信息
Argument of type 'StateCreator<ForestStore, [], [["zustand/persist", ForestStore]]>' is not assignable to parameter of type 'StateCreator<ForestStore, [], []>'. Type 'StateCreator<ForestStore, [], [["zustand/persist", ForestStore]]>' is not assignable to type '{ $$storeMutators?: [] | undefined; }'. Types of property '$$storeMutators' are incompatible. Type '[["zustand/persist", ForestStore]] | undefined' is not assignable to type '[] | undefined'. Type '[["zustand/persist", ForestStore]]' is not assignable to type '[]'. Source has 1 element(s) but target allows only 0.ts(2345)
问题原因
错误源于create<ForestStore>(forestPersist)的泛型指定:persist中间件返回的StateCreator带有中间件专属的类型标记([["zustand/persist", ForestStore]]),但手动给create指定的泛型是纯状态类型ForestStore,两者类型结构不匹配,导致TypeScript报错。
解决方案
有两种简单的修复方式:
方式1:让TypeScript自动推导类型
去掉create后的手动泛型指定,让TS自动识别persist返回的带中间件标记的类型:
import {create} from 'zustand'; import { persist, createJSONStorage} from 'zustand/middleware'; export type Forest = "poetry" | "prose" | "script"; export interface ForestStore { forest: Forest; setForest: (forest: Forest) => void; } const forestPersist = persist( (set) => ({ forest: "poetry", setForest: (newForest) => set(() => ({forest: newForest})), }), { name: "forest-storage", storage: createJSONStorage(() => sessionStorage), } ); // 移除手动指定的泛型,TS会自动推导正确类型 export const useForestStore = create(forestPersist);
方式2:显式指定包含中间件的类型
如果需要显式定义类型,可以声明包含persist中间件的StateCreator类型:
import {create, StateCreator} from 'zustand'; import { persist, createJSONStorage} from 'zustand/middleware'; export type Forest = "poetry" | "prose" | "script"; export interface ForestStore { forest: Forest; setForest: (forest: Forest) => void; } // 定义带有persist中间件标记的StateCreator类型 type PersistedForestStore = StateCreator< ForestStore, [], [["zustand/persist", ForestStore]] >; const forestPersist: PersistedForestStore = persist( (set) => ({ forest: "poetry", setForest: (newForest) => set(() => ({forest: newForest})), }), { name: "forest-storage", storage: createJSONStorage(() => sessionStorage), } ); export const useForestStore = create(forestPersist);
或者也可以给persist完整指定泛型参数,确保类型一致:
import {create} from 'zustand'; import { persist, createJSONStorage, PersistOptions} from 'zustand/middleware'; export type Forest = "poetry" | "prose" | "script"; export interface ForestStore { forest: Forest; setForest: (forest: Forest) => void; } // 给persist指定状态类型和持久化配置类型 const forestPersist = persist<ForestStore, PersistOptions<ForestStore>>( (set) => ({ forest: "poetry", setForest: (newForest) => set(() => ({forest: newForest})), }), { name: "forest-storage", storage: createJSONStorage(() => sessionStorage), } ); export const useForestStore = create(forestPersist);
内容的提问来源于stack exchange,提问作者Romen Medina Beltrán
相关产品推荐
相关产品推荐

