Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/react-query/src/__tests__/useQuery.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,25 @@ describe('useQuery', () => {
void result
})

// eslint-disable-next-line vitest/expect-expect
it('should preserve discriminated-union narrowing while keeping the reverse-inference guard', () => {
type Result =
| { type: 'first'; first: string }
| { type: 'second'; second: string }

const query = useQuery({
queryKey: queryKey(),
queryFn: (): Result => ({ type: 'first', first: 'a' }),
})

const second = query.data?.type === 'first' ? undefined : query.data

expectTypeOf(second).toEqualTypeOf<
| { type: 'second'; second: string }
| undefined
>()
})

it('data should not have undefined when initialData is provided', () => {
const { data } = useQuery({
queryKey: queryKey(),
Expand Down
8 changes: 5 additions & 3 deletions packages/react-query/src/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import type {
UseQueryOptions,
UseQueryResult,
} from './types'

type NarrowableNoInfer<T> = T extends unknown ? NoInfer<T> : never
import type {
DefinedInitialDataOptions,
UndefinedInitialDataOptions,
Expand All @@ -20,7 +22,7 @@ export function useQuery<
>(
options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): DefinedUseQueryResult<NoInfer<TData>, TError>
): DefinedUseQueryResult<NarrowableNoInfer<TData>, TError>

export function useQuery<
TQueryFnData = unknown,
Expand All @@ -30,7 +32,7 @@ export function useQuery<
>(
options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): UseQueryResult<NoInfer<TData>, TError>
): UseQueryResult<NarrowableNoInfer<TData>, TError>

export function useQuery<
TQueryFnData = unknown,
Expand All @@ -40,7 +42,7 @@ export function useQuery<
>(
options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
queryClient?: QueryClient,
): UseQueryResult<NoInfer<TData>, TError>
): UseQueryResult<NarrowableNoInfer<TData>, TError>

export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) {
return useBaseQuery(options, QueryObserver, queryClient)
Expand Down