Enforcing Type Safety in TypeScript Context

one for the typescript ninja's out there...is there a better way to do this such that i force the consumer of useRuntime to provide a generic so as to maintain some semblance of type safety? the RuntimeContext and useRuntime have no knowledge of the runtime to be used. but when using useRuntime for building other common libs, i still want to force the consumer to provide a tag or a service or something so that a check is made before its consumed.

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const RuntimeContext = createContext<RuntimeContextState<any, any> | undefined>(undefined);

export function useRuntime<R, ER = never>() {
  const context = useContext<RuntimeContextState<R, ER> | undefined>(RuntimeContext);

  if (typeof context === "undefined") {
    throw Error("useRuntime must be used within an RuntimeContext provider.");
  }

  return context.runtime;
}

function useSiteDetails() {
  const runtime = useRuntime();

  return useQuery({
    queryKey: ["site", 1444] as const,
    queryFn: (args) => {
      return Effect.gen(function* ($) {
        const service = yield* SiteService;
        return yield* service.getById({ id: args.queryKey[1] });
      }).pipe(runtime.runPromise);
    },
  });
}
Was this page helpful?