Defining Create with Typescript
Closed this issue · 1 comments
PaulFidika commented
First of all, thanks for creating this repo! I'm trying it out now.
I was wondering, how do you define "set" in typescript when creating the store? My original Zustand code used to look like this:
const useRoomState = create((set: SetState, get: GetState) => ({
...
But 'SetState' is not assignable with Zustand-addon's new create function. Any suggestions for what type to define set as?
Diablow commented
You're welcome Paul, I'm glad you are trying this out.
The addons setState uses a union type. I forgot to export the types but you can do the following:
import { GetState, PartialState, SetState, State } from "zustand"
import create from "zustand-store-addons";
interface SetStateSettings {
excludeFromLogs?: boolean | undefined;
replace?: boolean | undefined;
}
declare type SetStateAddons<T extends State> = (
partial: PartialState<T>,
setSettings?: SetStateSettings
) => void;
type AppStore = {
num: number;
generate: () => void;
}
const useAppStore = create(
(
set: SetStateAddons<AppStore> | SetState<AppStore>,
get: GetState<AppStore>
) => ({
num: 0,
generate: () =>
set({
num: Math.ceil(Math.random() * 100)
})
})
)
You can take a look at this example: https://codesandbox.io/s/zustand-store-addons-ts-example-4e6nc