type ContextProps<T = object> = {
store: T,
updateStore: React.Dispatch<T>
};
export default React.createContext<Partial<ContextProps>>({}); // is there any way to pass the generic? so store can correct type
export function Provider<T, K>(props: T & { store: K }) {
const [globalState, updateStore] = React.useState(props.store);
const value = React.useMemo(
() => ({
store: globalState,
updateStore,
}),
[globalState],
);
return <StateMachineContext.Provider value={value} {...props} />;
}
Is there any way to pass generic into Context, so value can have the correct type?
useContext<Type>(Context);. I think this is the best you are going to get as components making use of your context could appear under any instance of a provider for the context and each of these providers could have different generic types meaning typescript can't infer generic types for the consumer as it would have to assume the location of the component in the react tree. This is my understanding of it anyway.