使用 Typescript Generic React Context API

Bru*_*uce 3 typescript reactjs

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} />;
}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以将泛型传递到 Context 中,这样value就可以拥有正确的类型吗?

Jer*_*ryc 6

创建上下文时传递类型,记住在组件外部创建它。

type ContextProps<T = object> = {
  store: T,
  updateStore: React.Dispatch<T>
};

function createGenericContext<T extends object> () {
  return React.createContext<Partial<ContextProps<T>>>({}); 
}

const StateMachineContext = createGenericContext<{type: 'a'}>();
// or just
const StateMachineContext = React.createContext<Partial<ContextProps<{type: 'a'}>>>({});

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} />;
}
Run Code Online (Sandbox Code Playgroud)