Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a generic interface to zustand create call in TypeScript?

so I have been struggling with finding an answer, as to what is the correct syntax to pass an generic interface to a when calling a function that takes in a generic type.

What I want to do is const data = itemStore<T>(state => state.data)

import { create } from "zustand";

interface Item<T> {
  count: number
  data: T
}

const itemStore = create<Item<T>>()((set) => ({
  count: 1,
  data: "generic"
})
like image 929
Hawk Avatar asked Oct 21 '25 04:10

Hawk


1 Answers

Came back from the exile, here is your answer my friend:

// store file
type BaseStore<T> = {
  items: T;
};

const INITIAL_ITEMS_DATA: BaseStore<{}>['items'] = {};

const useDataImplementation = create<BaseStore<{}>>((set) => ({
  items: INITIAL_ITEMS_DATA,
}));

export const useStore = useDataImplementation as {
  <T>(): BaseStore<T>;
  <T, U>(selector: (s: BaseStore<T>) => U): U;
};

// Then when you call this thing you need to only pass your interface/type:
interface Item {
  name: string;
  price: string;
  stock: boolean;
}
const store = useStore<Item>();

With this you'll have your item nicely and strongly typed, so, we're asserting the types by making them to kinda lie.

like image 142
Liam Klyneker Avatar answered Oct 23 '25 14:10

Liam Klyneker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!