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"
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With