TanStack / query

🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
https://tanstack.com/query
MIT License
42.5k stars 2.91k forks source link

Missing generic TQueryKey in fetchQuery's QueryFunction signature #2099

Closed DiederikvandenB closed 3 years ago

DiederikvandenB commented 3 years ago

Describe the bug It seems recently some types changed in the package. Now, the following code is not validly typed anymore:

queryClient
  .fetchQuery(
    ['my-query', { filter: '' }],
    myQueryFunction
  );

Where myQueryFunction has the following type: QueryFunction<Response, QueryKey> and type QueryKey = ['my-query', { filter: string }];

This works though:

queryClient
  .fetchQuery(
    ['my-query', { filter: '' }],
    (myQueryFunction as QueryFunction<QueryResponse>)
  );

Expected behavior The generic types for fetchQuery, prefetchQuery, fetchInfiniteQuery, and prefetchInfiniteQuery should probably be updated to include the TQueryKey:

export declare class QueryClient {
  fetchQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey = unknown>(queryKey: QueryKey, queryFn: QueryFunction<TQueryFnData, TQueryKey>, options?: FetchQueryOptions<TQueryFnData, TError, TData>): Promise<TData>;
}

However, I don't know the React-Query codebase well enough to immediately start a PR.

Desktop (please complete the following information):

Additional context Full error:

[tsl] ERROR in file.tsx(65,9)
      TS2769: No overload matches this call.
  Overload 1 of 3, '(queryKey: QueryKey, options?: FetchQueryOptions<unknown, unknown, unknown> | undefined): Promise<unknown>', gave the following error.
    Type 'QueryFunction<Response, QueryKey>' has no properties in common with type 'FetchQueryOptions<unknown, unknown, unknown>'.
  Overload 2 of 3, '(queryKey: QueryKey, queryFn: QueryFunction<Response, QueryKey>, options?: FetchQueryOptions<Response, unknown, Response> | undefined): Promise<...>', gave the following error.
    Argument of type 'import("/node_modules/react-query/types/core/types").QueryFunction<import("/src/types/rcp").Response, QueryKey>' is not assignable to parameter of type 'import("/node_modules/react-query/types/core/types").QueryFunction<import("/src/types/rcp").Response, import("/node_modules/react-query/types/core/types").QueryKey>'.
      Type 'import("/node_modules/react-query/types/core/types").QueryKey' is not assignable to type 'QueryKey'.
        Type 'string' is not assignable to type '["Response", string]'.
TkDodo commented 3 years ago

yes, we recently added type inference for the query key on the queryFunction. before that, it was always string | Array<unknown>.

I think you are right with passing the generic through - can you maybe PR that?

DiederikvandenB commented 3 years ago

Opened PR #2100, I think it's best if we close this issue and continue any necessary discussions there.