0

I have created the following store using Zustand:

import create from "zustand"

const useStore = create((set) => ({
  show: false,
  toggleShow: () => set((state) => ({ show: !state.show })),
}))

I assumed that this would be the correct way to toggle the value of show. However, typescript is not happy -- it has a red squiggly line underneath the show in !state.show with the following error message:

Property 'show' does not exist on type 'object'.ts(2339)
any

Any idea why I am getting that error message and how I can properly set up a toggle function using Zustand?

Thanks.

YSK
  • 528
  • 4
  • 7
Moshe
  • 6,011
  • 16
  • 60
  • 112

1 Answers1

2

Typescript doesn't know what you state should look like, so it assumes that the state is a plain object.

To solve this, you can define a type for your store. Then, you can pass that type to the create function as a generic:

type MyStore = {
    show: boolean;
    toggleShow: () => void;
};

// note the "<MyStore>" next to create
const useStore = create<MyStore>((set) => ({
    show: false,
    toggleShow: () => set((state) => ({ show: !state.show})),
}))

This makes typescript aware of which properties to expect to be in your store. It will no longer throw an error for the !state.show part, and it will be offering meaningful autocomplete whenever you use the store.

YSK
  • 528
  • 4
  • 7