Skip to content

Passing a TypeScript Generic to the store's type #362

Closed Answered by dai-shi
zorzysty asked this question in Q&A
Discussion options

You must be logged in to vote

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)

Replies: 1 comment 9 replies

Comment options

You must be logged in to vote
9 replies
@dai-shi
Comment options

@zorzysty
Comment options

@dai-shi
Comment options

@zorzysty
Comment options

@dai-shi
Comment options

Answer selected by zorzysty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants