NextJS + Zustand + TypeScript type conflict with persist middleware

--

Just a short note for me again :)

Found some issues while building a project with NextJS and got type error on a persist function ( here is an example before )

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

type T = {
accessToken: string | null;
setAccessToken: (token: string) => void;
}

const useAuthStore = create<T>(
persist(
(set, get): T => ({
accessToken: null,
setAccessToken: (token) => set((state) => ({ accessToken: token })),
}),
{
name: 'auth',
storage: createJSONStorage(() => localStorage),
},
),
);

export default useAuthStore;

And I got this error on the build….

./src/state/useAuthStore.ts:10:3
Type error: Argument of type 'StateCreator<T, [], [["zustand/persist", unknown]]>' is not assignable to parameter of type 'StateCreator<T, [], []>'.
Type 'StateCreator<T, [], [["zustand/persist", unknown]]>' is not assignable to type '{ $$storeMutators?: [] | undefined; }'.
Types of property '$$storeMutators' are incompatible.
Type '[["zustand/persist", unknown]] | undefined' is not assignable to type '[] | undefined'.
Type '[["zustand/persist", unknown]]' is not assignable to type '[]'.
Source has 1 element(s) but target allows only 0.

And here is an example of a way to solve type on this

import { create, StateCreator } from 'zustand';
import { createJSONStorage, persist, PersistOptions } from 'zustand/middleware';

type AuthStore = {
accessToken: string | null;
setAccessToken: (token: string) => void;
}

type MyPersist = (
config: StateCreator<AuthStore>,
options: PersistOptions<AuthStore>
) => StateCreator<AuthStore>

const useAuthStore = create<AuthStore, []>(
(persist as MyPersist)(
(set, get): AuthStore => ({
accessToken: null,
setAccessToken: (token: string) => set((state) => ({ accessToken: token })),
}),
{
name: 'auth',
storage: createJSONStorage(() => localStorage),
},
),
);

export default useAuthStore;

Thx, dai-shi
ref: https://github.com/pmndrs/zustand/issues/650#issuecomment-965916156

--

--