Typescript

zustand persist에 타입 제공하기

띵킹 2023. 8. 26. 12:32

전역 상태인 AuthState를 LocalStorage에서 사용하기 위헤 store 객체를 persist로 감쌌더니, 타입 에러가 발생했다.

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

아래와 같이 StateCreator 타입과 PersistOptions 타입을 불러온 후,

persist 인자에 단언해줄 타입을 생성하면 해결된다.

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

interface UserData {
...
}

export interface AuthState {
....
}

export type AuthStatePersist = (
  config: StateCreator<AuthState>,
  options: PersistOptions<AuthState> 
) => StateCreator<AuthState>

const useAuthStore = create<AuthState>(
  (persist as AuthStatePersist)(
    (set, get) => ({
      user: null,
      isLoggedIn: false,
      login: (userData: UserData) => {
        set({ isLoggedIn: true, user: userData });
      },
      logout: () => {
        set({ isLoggedIn: false, user: null });
      },
    }),
    {
      name: 'user-storage',
    },
  ),
);

728x90