جافاسكريبت - خطأ TypeScript مع وسيط التخزين الدائم (Persist Middleware) وStateCreator في تطبيق React


أحاول استخدام الوسيط persist في Zustand لتخزين واسترجاع الحالة في تطبيقي React. ومع ذلك، أواجه خطأ في 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)

إليك شفرتي:

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<ForestStore>(
    (set) => ({
        forest: "poetry",
        setForest: (newForest) => set(() => ({forest: newForest})),
    }),
    {
        name: "forest-storage",
        storage: createJSONStorage(() => sessionStorage),
    }
);



export const useForestStore = create<ForestStore>(forestPersist);

أنا حقًا لا أعرف كيفية حلها، فالرمز يعمل كما هو مقصود لكن الأنواع تسبب مشاكل.

شكراً جزيلاً لك مقدمًا

الإجابة رقم 1

اكتبها بهذه الطريقة

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;
}

const forestSlice: StateCreator<ForestStore, [["zustand/persist", unknown]]> = (
  set
) => ({
  forest: "poetry",
  setForest: (newForest) => set(() => ({ forest: newForest })),
});

export const useForestStore = create<ForestStore>()(
  persist(forestSlice, {
    name: "forest-storage",
    storage: createJSONStorage(() => sessionStorage),
  })
);

إذا كان لديك المزيد من الوسائط الوسيطة مثل devtools، immer و subscribeWithSelector، يمكنك إلقاء نظرة على الفيديو الخاص بي، الكود في هذا الفيديو تم اختباره:

https://youtu.be/kTwx9NhMlzs

الإجابة رقم 2

كما قال محمد نعمان رفيق:

أضف() بعد create هكذا: const useForestStore=create()(forestPersist). هذا سيحل مشكلة النوع