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
7 changes: 7 additions & 0 deletions .changeset/vue-query-narrow-result-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@tanstack/vue-query': patch
---

fix(vue-query): preserve discriminated union narrowing in `UseBaseQueryReturnType`

Make the mapped type explicitly distributive over each variant of `QueryObserverResult`, and document the narrowing patterns that work without `reactive()` (direct `data.value !== undefined` checks) versus those that require `reactive()` (narrowing via `isSuccess`/`status`). Adds type-test coverage for the issue scenario.
2 changes: 2 additions & 0 deletions docs/framework/vue/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ if (isSuccess) {

[typescript playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgVwM4FMCKz1QJ5wC+cAZlBCHAOQACMAhgHaoMDGA1gPQBuOAtAEcc+KgFgAUKEixEcKOnqsYwbuiKlylKr3RUA3BImsIzeEgAm9BgBo4wVAGVkrVulSp1AXjkKlK9AAUaFjCeAEA2lQwbjBUALq2AQCUcJ4AfHAACpr26AB08qgQADaqAQCsSVWGkiRwAfZOLm6oKQgScJ1wlgwSnJydAHoA-BKEEkA)

> **Note:** Wrapping `useQuery(...)` in `reactive(...)` is required to narrow `data` from a discriminator like `isSuccess` or `status`. Destructuring directly from `useQuery(...)` produces independent refs, and TypeScript cannot propagate narrowing across separate refs — `if (isSuccess.value)` will not narrow `data.value` from `T | undefined` to `T`. If you cannot use `reactive()`, narrow the value ref directly with `if (data.value !== undefined)`.

[//]: # 'TypeNarrowing'
[//]: # 'TypingError'

Expand Down
95 changes: 95 additions & 0 deletions packages/vue-query/src/__tests__/useQuery.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { describe, expectTypeOf, it } from 'vitest'
import { computed, reactive, ref } from 'vue-demi'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { queryOptions, useQuery } from '..'
import type { Ref } from 'vue-demi'
import type { QueryObserverResult } from '@tanstack/query-core'
import type { OmitKeyof, UseQueryOptions } from '..'

describe('useQuery', () => {
Expand Down Expand Up @@ -268,6 +270,99 @@ describe('useQuery', () => {
})
})

// Regression coverage for #9244 — narrowing across the discriminated
// result union from useQuery() under the patterns users actually write.
describe('issue #9244 — narrowing without reactive()', () => {
it('useQuery() return preserves the discriminated union (no reactive())', () => {
const key = queryKey()

const query = useQuery({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
})

// Whole-result narrowing requires reactive() because the discriminator
// sits inside `Ref<boolean>`. The `data` ref itself is still a
// discriminated union of `Ref<string> | Ref<undefined>` (matches the
// shape documented in docs/framework/vue/typescript.md).
expectTypeOf(query.data).toEqualTypeOf<Ref<string> | Ref<undefined>>()
})

it('data.value narrows after a direct undefined check', () => {
const key = queryKey()

const { data } = useQuery({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
})

// This is the recommended pattern when `reactive()` is not used:
// narrow on `.value !== undefined` rather than relying on `isSuccess`.
if (data.value !== undefined) {
expectTypeOf(data.value).toEqualTypeOf<string>()
expectTypeOf(data).toEqualTypeOf<Ref<string>>()
}
})

it('reactive() preserves narrowing across destructured properties', () => {
const key = queryKey()

// Destructuring directly from `useQuery()` (without `reactive()`)
// breaks cross-property narrowing because each ref is independent —
// wrapping in `reactive()` flattens the refs and keeps the
// discriminated union linkage.
const { data, isSuccess } = reactive(
useQuery({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}),
)

if (isSuccess) {
expectTypeOf(data).toEqualTypeOf<string>()
}
})

it('reactive() narrows on status discriminator', () => {
const key = queryKey()

const { data, status } = reactive(
useQuery({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}),
)

if (status === 'success') {
expectTypeOf(data).toEqualTypeOf<string>()
}
})

it('suspense() returns Promise<QueryObserverResult> parameterized by TResult', async () => {
const key = queryKey()

const query = useQuery({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
})

// Pinning the resolved type guards the `suspense: () => Promise<TResult>`
// parameterization on `UseBaseQueryReturnType` against accidental
// collapse to `Promise<unknown>` or `Promise<QueryObserverResult<unknown, unknown>>`.
expectTypeOf(query.suspense()).toEqualTypeOf<
Promise<QueryObserverResult<string, Error>>
>()

const result = await query.suspense()
// Awaiting the promise must preserve the discriminated union so
// narrowing on `isSuccess` reduces `data` to the queryFn return type.
if (result.isSuccess) {
expectTypeOf(result.data).toEqualTypeOf<string>()
expectTypeOf(result.error).toEqualTypeOf<null>()
}
})
})

describe('accept ref options', () => {
it('should accept ref options', () => {
const options = ref({
Expand Down
25 changes: 17 additions & 8 deletions packages/vue-query/src/useBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,27 @@ import type { UseQueryOptions } from './useQuery'
import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
import type { MaybeRefOrGetter } from './types'

// Distributive over `TResult` so each member of the discriminated union
// (success / pending / error / placeholder / refetch-error / loading-error)
// produces its own ref-mapped object, instead of collapsing into a single
// `{ data: Ref<TData | undefined>, ... }`. This preserves narrowing through
// `reactive()` and direct property access on the un-destructured result.
// See packages/vue-query/src/__tests__/useQuery.test-d.ts for the contracts
// this preserves (and the destructure-without-reactive limitation).
export type UseBaseQueryReturnType<
TData,
TError,
TResult = QueryObserverResult<TData, TError>,
> = {
[K in keyof TResult]: K extends
| 'fetchNextPage'
| 'fetchPreviousPage'
| 'refetch'
? TResult[K]
: Ref<Readonly<TResult>[K]>
} & {
> = (TResult extends unknown
? {
[K in keyof TResult]: K extends
| 'fetchNextPage'
| 'fetchPreviousPage'
| 'refetch'
? TResult[K]
: Ref<Readonly<TResult>[K]>
}
: never) & {
suspense: () => Promise<TResult>
}

Expand Down
Loading