1

when I create my store object separately from the hook and do not assign any type to "set", TS is showing me a type error. Is there any specific type I can throw at it or should I leave it as any? Couldn't find anything about it in the documentation.

The store looks as follows:

const templateStore = (set: any) => ({
    borderRadius: 12,
    drawerWidth: 250,
    fontFamily: `'Roboto', sans-serif`',
    headerHeight: 80,
    language: 'UK',
    opened: true,
    setLang: (lang: string) => set({ language: lang }),
    setMenu: () => set((state: TemplateStore) => ({ opened: !state.opened })),
});

And the hook:

const useTemplateStore = create<TemplateStore>()(
    devtools(
        persist(templateStore, {
            name: 'template',
        }),
    ),
);

I tried assigning the TemplateStore interface, which didn't work and also the any type which is not desired.

CzechCoder
  • 33
  • 5

1 Answers1

0

You can use zustand StoreCreator generic type. Import the type and pass store interface to StoreCreator and then use that type for templateStore.

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

interface TemplateStore {
    borderRadius: number;
    drawerWidth: number;
    fontFamily: string;
    headerHeight: number;
    language: string;
    opened: boolean;
    setLang: (lang: string) => void;
    setMenu: () => void;
}

type CustomStoreType = StateCreator<TemplateStore>;

const templateStore: CustomStoreType = (set, get) => ({
    borderRadius: 12,
    drawerWidth: 250,
    fontFamily: `'Roboto', sans-serif`,
    headerHeight: 80,
    language: 'UK',
    opened: true,
    setLang: (lang) => set({ language: lang }),
    setMenu: () => set((state) => ({ opened: !state.opened }))
});

const useTemplateStore = create<TemplateStore>()(
    devtools(
        persist(templateStore, {
            name: 'template'
        })
    )
);

export default useTemplateStore;