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
16 changes: 16 additions & 0 deletions docs/framework/vue/typescript.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -68,6 +68,22 @@ if (isSuccess) {

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

The `reactive()` wrapper is what makes this work: it flattens the result into
plain values, so `isSuccess` and `data` stay part of the same discriminated
union. Destructuring `useQuery()` directly gives you independent refs, and
TypeScript cannot carry a narrowing from one ref to another — `if (isSuccess.value)`
leaves `data.value` as `Group[] | undefined`. Without `reactive()`, narrow the
value ref itself:

```tsx
const { data } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })

if (data.value !== undefined) {
data.value
// ^? const data: Group[]
}
```

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

Expand Down
26 changes: 26 additions & 0 deletions packages/vue-query/src/__tests__/useQuery.test-d.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@ import { assertType, 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 { OmitKeyof, UseQueryOptions, UseQueryReturnType } from '..'

describe('useQuery', () => {
Expand DownExpand Up@@ -289,6 +290,31 @@ describe('useQuery', () => {
expectTypeOf(query.error).toEqualTypeOf<Error>()
}
})

it('data should be a union of refs without reactive()', () => {
const key = queryKey()

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

expectTypeOf(query.data).toEqualTypeOf<Ref<string> | Ref<undefined>>()
})

it('data.value should narrow on an undefined check without reactive()', () => {
const key = queryKey()

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

if (data.value !== undefined) {
expectTypeOf(data.value).toEqualTypeOf<string>()
expectTypeOf(data).toEqualTypeOf<Ref<string>>()
}
})
})

describe('accept ref options', () => {
Expand Down