-
I need to pass a TS generic to the type describing the store, but I can't figure out how to pass it through the I'm hoping to achieve something similar to the code below, but here of course the // inside the store file
type State<Bear> = {
bears: Bear[]
increase: (newBear: Bear) => void
}
export const useStore = create<State<Bear>>((set) => ({
bears: [],
increase: (newBear) => set((state) => ({ bears: [...state.bears, newBear] })),
}))
// and in a file using the store
type Bear = {
kind: "Grizzly" | "Polar"
age: number
}
const bears = useStore<Bear>((state) => state.bears) I tried to wrap the result of Inb4, I can't declare the Is there a way to do it properly? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
I don't know if there's a TS-only way. If we can use a wrapper, something like this? const useStoreUnknown = create<State<unknown>>((set) => ({
bears: [],
increase: (newBear) => set((state) => ({ bears: [...state.bears, newBear] })),
}))
export const useStore = <Bear>(selector StateSelector<State<Bear>>): State<Bear> => useStoreUnknown(selector) Or, maybe this works? export const useStore = create<State<unknown>>((set) => ({
bears: [],
increase: (newBear) => set((state) => ({ bears: [...state.bears, newBear] })),
}))
// in component
const bears = useStore<State<Bear>>((state) => state.bears) |
Beta Was this translation helpful? Give feedback.
I don't know if there's a TS-only way. If we can use a wrapper, something like this?
Or, maybe this works?