TypeScript errors when using exported queryOptions factory in @tanstack/react-query 5.62.8 #8453
Send to my agentDescribe the bug#
When using the factory queryOptions and exporting the result, TypeScript errors appear:
Exported variable 'shopsQuery' has or is using name 'dataTagErrorSymbol' from external module "/node_modules/@tanstack/query-core/build/legacy/hydration-DiTAi-4H" but cannot be named. (ts4023)
Exported variable 'shopsQuery' has or is using name 'dataTagSymbol' from external module "/node_modules/@tanstack/query-core/build/legacy/hydration-DiTAi-4H" but cannot be named. (ts4023)
These errors occur in every instance where I export the result of queryOptions. Removing the export resolves the issue, but that isn't an acceptable workaround.
Your minimal, reproducible example#
Steps to reproduce#
- Install the latest version of @tanstack/react-query (v5.62.8).
- Create and export a variable using
queryOptionsfactory, e.g.,export const shopsQuery = queryOptions(...);. - Observe TypeScript errors as described.
Expected behavior#
The queryOptions factory should allow exporting without triggering TypeScript errors.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
- OS [Windows, Linux]
Tanstack Query adapter#
react-query
TanStack Query version#
v5.62.8
TypeScript version#
v5.7.2
Additional context#
No response
@TkDodo @Nick-Lucas I'm getting comments about typing problems since v5.62.8 / #8394 on Angular too, e.g.: https://github.com/TanStack/query/discussions/6293#discussioncomment-11647295
@TkDodo @Nick-Lucas I'm getting comments about typing problems since v5.62.7 / #8394 on Angular too, e.g.: https://github.com/TanStack/query/discussions/6293#discussioncomment-11647295
I've seen this too in the tRPC codebase, returning a datatagged thing (query key, query options, etc) shows a portability error unless you explicitly type the return - as a workaround that's the solution
I'm not entirely sure right now how to prevent it but I know it's a common problem in libs
@juliusmarminge we've solved this for tRPC before, right?
@juliusmarminge we've solved this for tRPC before, right?
Did you create some new types that aren't exported from a public entrypoint? That's usually a primary cause.
But RQ is, and never will be with the current behaviors in TypeScript, not fully portable since it relies on
@tanstack/query-coreinternals that users doesn't automatically install. This is the case for all libs that relies on a "core" package. A fix for those cases is that the user installs both libs explicitly which makes it easier for TypeScript to discover the scanned paths when emitted the declaration files.Interestingly
dataTagSymbolhas been there for a year, so it's weird that one's causing a problem now.dataTagErrorSymbolis newish but since a few releases before 5.62.7Perhaps the root is is simply that
queryOptionsis now more correctly typed and so call sites where this wasn't an issue before are now an issue?Are all types used for data tags and queryOptions exported from the main RQ entrypoint? Are any re-exports from core package?
EDIT: Ah the symbols are from core package. Can they not be defined and exported in the framework package? I think that might help TS discover them more easily. IIRC last time I looked at queryOptions stuff all types are in each framework package so why can't the data tags also be there?
In this case no these symbols aren't exported by either query-core or rq/angular directly, I will play with an MR which changes this as we already have a reproduction in tRPC that I can test against
Some workarounds in the mean-time:
- If you have an application then you may not need tsconfig to have
compilerOptions.declaration: true- setting it false should squash the error - If you have a library then explicitly defining your return types should squash the issue (also true in apps, but more annoying)
- If you have an application then you may not need tsconfig to have
If you have an application then you may not need tsconfig to have compilerOptions.declaration: true - setting it false should squash the error
definitely need
declaration: truefor monoreposIn this case no these symbols aren't exported by either query-core or rq/angular directly, I will play with an MR which changes this as we already have a reproduction in tRPC that I can test against
we can export the symbols from the core, no problem.
Can they not be defined and exported in the framework package?
no, because core things in the
queryClientneed them, too (seequeryClient.getQueryData)TkDodo added labelstypes
In this case no these symbols aren't exported by either query-core or rq/angular directly
@Nick-Lucas as far as I can see, we do export the symbols:
I can also import them from
@tanstack/react-querydirectly.same here
I can also import them from
@tanstack/react-querydirectly.Yes that's what I want to ensure is happening, hard to trace through barrel files though, back online now so I'll take a look
Okay so some investigation against tRPC's new client where I have observed the issue when returning
queryOptions()- Firstly
dataTagSymbolanddataTagErrorSymbolare indeed exported by react-query via barrel so no issues there - Adding @tanstack/query-core as a dependency to the project does not fix it
- Importing
dataTagSymbolanddataTagErrorSymbolfrom react-query does make the error go away, comes with the need to ignore unused dependencies errors in eslint but I think this is the easiest workaround for now
I noticed the way symbols are declared is different from tRPC though, and switching over does seem to work, though I don't really know what the difference is
https://github.com/TanStack/query/pull/8468
No error:
ChatGPT (Link to chat) informs me that the declare keyword is just a declaration without an implementation, but the tRPC way actually creates a concrete symbol which we can then draw a type declaration from. That may explain why typescript isn't behaving as people describe, the type needs to have an implementation to be inferable via a library later - I'd love to understand this more but I don't
- Firstly
TkDodo closed this
Hey folks, i don't think this is properly fixed. The output d.ts is using a symbol without being imported and thus, resulting into incorrect d.ts files
Given this input:
import { queryOptions } from "@tanstack/react-query" export const exported = queryOptions({ queryKey: ['invalid'], })Here is the d.ts output:
export declare const exported: import("@tanstack/react-query").OmitKeyof<import("@tanstack/react-query").UseQueryOptions<unknown, Error, unknown, string[]>, "queryFn"> & { queryFn?: import("@tanstack/react-query").QueryFunction<unknown, string[], never> | undefined; } & { queryKey: string[] & { [dataTagSymbol]: unknown; [dataTagErrorSymbol]: Error; }; };And both symbols are not imported :/
A minimal reproduction can be looked at https://tsplay.dev/w2O6bN
A reproduction can be looked at https://github.com/TanStack/router/pull/3078 , then running
pnpm installand thenpnpm nx run router-monorepo-react-query:devOutput per version, regarding the mono example on tanstack/router#
Input:
import { queryOptions } from '@tanstack/react-query' import { fetchPost } from './posts' export const postQueryOptions = (postId: string) => queryOptions({ queryKey: ['posts', { postId }], queryFn: () => fetchPost(postId), })React Query 5.62.7 output:
export declare const postQueryOptions: (postId: string) => import('@tanstack/react-query').OmitKeyof<import('@tanstack/react-query').UseQueryOptions<import('./posts').PostType, Error, import('./posts').PostType, import('@tanstack/react-query').QueryKey>, "queryFn"> & { queryFn?: import('@tanstack/react-query').QueryFunction<import('./posts').PostType, import('@tanstack/react-query').QueryKey, never> | undefined; } & { queryKey: import('@tanstack/react-query').DataTag<import('@tanstack/react-query').QueryKey, import('./posts').PostType>; };React Query 5.62.8 output (no d.ts at all):
src/postQueryOptions.tsx:4:14 - error TS4023: Exported variable 'postQueryOptions' has or is using name 'dataTagErrorSymbol' from external module "/Users/nicolasbeaussart-hatchuel/work/perso/git/tanstack/router/node_modules/.pnpm/@tanstack+query-core@5.62.8/node_modules/@tanstack/query-core/build/modern/hydration-DiTAi-4H" but cannot be named. 4 export const postQueryOptions = (postId: string) => ~~~~~~~~~~~~~~~~ src/postQueryOptions.tsx:4:14 - error TS4023: Exported variable 'postQueryOptions' has or is using name 'dataTagSymbol' from external module "/Users/nicolasbeaussart-hatchuel/work/perso/git/tanstack/router/node_modules/.pnpm/@tanstack+query-core@5.62.8/node_modules/@tanstack/query-core/build/modern/hydration-DiTAi-4H" but cannot be named. 4 export const postQueryOptions = (postId: string) =>That was fixed with https://github.com/TanStack/query/pull/8468
However, with react Query 5.62.9, compile dts but type check is not passing, here is the d.ts:
export declare const postQueryOptions: (postId: string) => import('@tanstack/react-query').OmitKeyof<import('@tanstack/react-query').UseQueryOptions<import('./posts').PostType, Error, import('./posts').PostType, (string | { postId: string; })[]>, "queryFn"> & { queryFn?: import('@tanstack/react-query').QueryFunction<import('./posts').PostType, (string | { postId: string; })[], never> | undefined; } & { queryKey: (string | { postId: string; })[] & { [dataTagSymbol]: import('./posts').PostType; [dataTagErrorSymbol]: Error; }; };However, both symbol are assumed global, but aren't defined globally
That's really unusual and I'm not sure what could be wrong here
Couldn't get the tsplayground to reproduce, but the router PR is definitely not behaving how I would expect
> pnpm nx run @router-mono-react-query/post-query:buildMy best idea was the types needed explicitly exporting from query-core and react-query, but that hasn't helped: https://github.com/TanStack/query/pull/8481/files
tsconfig's
skipLibCheckwill hide the error though I understand that's not right for many projectsCouldn't get the tsplayground to reproduce
You can see it on the ts playground in the link I've mentioned tsplay.dev/w2O6bN, and then go to the
d.tstab on the righttsconfig's skipLibCheck will hide the error though I understand that's not right for many projects
That could be a workaround, but that dosen't change the fact that the symbol is assumed global, without a global definition :/
What is weird is that previous to 5.62.8, the query key is using a generic
export declare const postQueryOptions: (postId: string) => import('@tanstack/react-query').OmitKeyof<import('@tanstack/react-query').UseQueryOptions<import('./posts').PostType, Error, import('./posts').PostType, import('@tanstack/react-query').QueryKey>, "queryFn"> & { queryFn?: import('@tanstack/react-query').QueryFunction<import('./posts').PostType, import('@tanstack/react-query').QueryKey, never> | undefined; } & { queryKey: import('@tanstack/react-query').DataTag<import('@tanstack/react-query').QueryKey, import('./posts').PostType>; };where as post 5.62.9, the query key type is computed (instead of using the generic), resulting in wrong reference
export declare const postQueryOptions: (postId: string) => import('@tanstack/react-query').OmitKeyof<import('@tanstack/react-query').UseQueryOptions<import('./posts').PostType, Error, import('./posts').PostType, (string | { postId: string; })[]>, "queryFn"> & { queryFn?: import('@tanstack/react-query').QueryFunction<import('./posts').PostType, (string | { postId: string; })[], never> | undefined; } & { queryKey: (string | { postId: string; })[] & { [dataTagSymbol]: import('./posts').PostType; [dataTagErrorSymbol]: Error; }; };So I don't know what change in https://github.com/TanStack/query/pull/8394/ is making the DataDat not being used via the generic and instead resolving it, that is causing the issue here
Done some more looking into this and honestly I'm lost.
It makes sense why
[dataTagErrorSymbol]: Error;couldn't be[import(...).dataTagErrorSymbol]: Error;because it's a value and import() returns a promiseBut deciding to inline and producing invalid code just makes it seem like a typescript bug. Why not continue to reference the generic import if it can't be inlined correctly?
arnoud-dv(GitHub profile, opens in a new tab) reopened this
birkskyum(GitHub profile, opens in a new tab) added labelspackage: react-query
Are there any updates on this? It's been months and numerous people have thumbs upped the issue. This has prevented us from upgrading since the problematic release.
@Nick-Lucas
Done some more looking into this and honestly I'm lost.
It makes sense why
[dataTagErrorSymbol]: Error;couldn't be[import(...).dataTagErrorSymbol]: Error;because it's a value and import() returns a promiseBut deciding to inline and producing invalid code just makes it seem like a typescript bug. Why not continue to reference the generic import if it can't be inlined correctly?
No, in
.d.tstermstype X = import(...).Yis not a promise - it's not a dynamic import syntax - it's import alias (functionally equal toimport _X from '...'; type X = _X.Y;or somethilng like that), it's used in order to preserve exising imports (inserting new imports might be unsafe for runtime).The problem with this:
import { queryOptions } from '@tanstack/react-query' import { fetchPost } from './posts' export const postQueryOptions = (postId: string) => queryOptions({ queryKey: ['posts', { postId }], queryFn: () => fetchPost(postId), })being expanded to this:
export declare const postQueryOptions: (postId: string) => import('@tanstack/react-query').OmitKeyof<import('@tanstack/react-query').UseQueryOptions<import('./posts').PostType, Error, import('./posts').PostType, (string | { ... [dataTagSymbol]: import('./posts').PostType; [dataTagErrorSymbol]: Error;and then failing to import the symbol is that
dataTagSymbolis exported in@tanstack/query-core, not in@tanstack/react-query, meaning, the symbol is local in relation to@tanstack/react-query, and thustsccan't just add an import to it 'cause@tanstack/query-coreis not guaranteed to be in the consuming code'sdependencies, and tsc can't just create an import for a module, that can just not be there (f.e. it is actualy inlined/bundled by @tanstack/react-query, but tsc has no way to know that while analyzing it's .d.ts)The most likely cause of
postQueryOptions's return type being expanded i thatqueryOptionsreturn type is an intersection typeXXX & { queryKey: DataTag<...> }If you instead move thequeryKeyinside theXXXtype declaration, tsc would not try to expand the intersection and allow it to be inferred instead:export function queryOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, >( options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, ): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & { queryKey: DataTag<TQueryKey, TQueryFnData, TError> }change to
export type DefinedInitialDataOptions< ... > = Omit<UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & { queryFn?: ... queryKey: DataTag<TQueryKey, TQueryFnData, TError> }Repeat for all overloads of
queryOptionsandinfiniteQueryOptions.I'm running into this issue building the new Better Auth UI query hooks. See my queryOptions:
import { type DataTag, queryOptions, type UseQueryOptions } from "@tanstack/react-query" import type { BetterFetchError } from "better-auth/react" import type { AuthClient } from "../../lib/auth-clients/auth-client" export type SessionData<TAuthClient extends AuthClient> = TAuthClient["getSession"] extends ( ...args: infer _Args ) => Promise<infer TResult extends { data: unknown }> ? TResult["data"] : never export type SessionParams<TAuthClient extends AuthClient> = Parameters<TAuthClient["getSession"]>[0] export type SessionOptions<TAuthClient extends AuthClient> = Omit< ReturnType<typeof sessionOptions<TAuthClient>>, "queryKey" | "queryFn" > export function sessionOptions<TAuthClient extends AuthClient>( authClient: TAuthClient, params?: SessionParams<TAuthClient> ) { type TData = SessionData<TAuthClient> const queryKey = ["auth", "getSession", params?.query ?? null] as const const options = queryOptions<TData, BetterFetchError, TData, typeof queryKey>( { queryKey, queryFn: ({ signal }) => authClient.getSession({ ...params, fetchOptions: { ...params?.fetchOptions, signal, throw: true } }) as Promise<TData> } ) return options as typeof options & { queryKey: DataTag<typeof queryKey, TData, BetterFetchError> } }I need to manually declare the DataTag, this seems quite redundant sadly. This is required in order for setQueryData to have types in consumers. Please advise if there is a better way to resolve this 🙏 @TkDodo
I’m not getting any errors with the latest version of TypeScript and React Query in the original playground.
I’d appreciate another failing playground to take a look at.
For
@tanstack/vue-query, this is a failing playground. The issue happens only for versions of@tanstack/vue-queryabove 5.97.0, including the current version of 5.100.1. https://www.typescriptlang.org/play/?ts=5.9.3#code/JYWwDg9gTgLgBAbzgRwK4FMoE8DyYbAQB2AznAL5wBmUEIcARAAIwCGpbAxgNYD0AbhgC0aTFgYBYAFDTOxEvDlQo6TjACKGbHgLy4AXhRbc+QqQAUCaXCNiA0uiwAuOAG0A5EpVr3AXQA00uQAlNJhUugAHpCwcHIccMBE-KwANsAAJppiOmZkhqLapvKW1rbYDs5u7kkp6Rl+gVIhQAThe error is similar:
The inferred type of 'invalidQueryOptions' references an inaccessible 'unique symbol' type. A type annotation is necessary.The failing code is:
import { queryOptions } from "@tanstack/vue-query" export const invalidQueryOptions = queryOptions({ queryKey: ['invalid'], })TkDodo closed this
Sign in to join this conversation.
I got the same problem as well in
v5.62.8but no problem inv5.62.7.