Replies: 2 comments 3 replies
-
The type inference is actually pretty layered, and complex, and difficult to recreate easily. Is there any reason why you’re trying to manually type this and not just letting automatic inference take over (like in the React Query example)? |
Beta Was this translation helpful? Give feedback.
3 replies
-
I put together this quick GET helper. Maybe someone can expand it or improve it. 😅 import { useQuery, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
import createClient from "openapi-fetch";
import type { FetchOptions, FetchResponse } from "openapi-fetch";
import type { PathsWithMethod, FilterKeys } from "openapi-typescript-helpers";
import { paths } from "../api";
const client = createClient<paths>();
export function useGet<
Path extends PathsWithMethod<paths, 'get'>,
Init extends FetchOptions<FilterKeys<paths[Path], 'get'>>,
Response extends FetchResponse<paths[Path]['get']>['data'],
>(
path: Path,
init: Init,
query?: Partial<UseQueryOptions>) {
return useQuery({
...query,
queryKey: [path, init?.params, init?.body],
queryFn: async ({ signal }) => {
const { data, error, response } = await client.GET(path, { ...init, signal });
if (error) {
if (response.status == 403) {
// Unauthorized
}
throw new Error(error as string);
}
return data;
},
}) as UseQueryResult<Response>;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm just trying to write a little helper here, but I seem to be missing something. I've tried all variations of types for
path
but I can't seem to find the right one to satisfy everything.The typescript error that path gives is
I'm not quite sure how to type
path
so that it will fitI'm not sure how this one doesn't get the same error
Beta Was this translation helpful? Give feedback.
All reactions