T
TanStack3y ago
absent-sapphire

Bug? Unable to narrow the discriminated union type for vue-query

Failed to narrow the data type from a discriminated union when using vue-query A minimal example below
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'

const { isSuccess, data } = useQuery({
queryKey: ['test3'],
queryFn: (): Promise<{ name: string }> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: 'Susan' })
}, 1000)
})
}
})

if (isSuccess.value) {
console.log(data.value.name)
}
</script>
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'

const { isSuccess, data } = useQuery({
queryKey: ['test3'],
queryFn: (): Promise<{ name: string }> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: 'Susan' })
}, 1000)
})
}
})

if (isSuccess.value) {
console.log(data.value.name)
}
</script>
Got this type error:
src/components/Test3.vue:16:15 - error TS18048: 'data.value' is possibly 'undefined'.

16 console.log(data.value.name)
src/components/Test3.vue:16:15 - error TS18048: 'data.value' is possibly 'undefined'.

16 console.log(data.value.name)
Was planning to create a github issue but since I'm new to vue-query (coming from react-query), I'd like to ask before opening one.
1 Reply
absent-sapphire
absent-sapphireOP3y ago
Using it in the template:
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'

const { isSuccess, data } = useQuery({
queryKey: ['test2'],
queryFn: (): Promise<{ name: string }> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: 'Susan' })
}, 1000)
})
}
})
</script>

<template>
<div v-if="isSuccess">
{{ data.name }}
</div>
</template>
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'

const { isSuccess, data } = useQuery({
queryKey: ['test2'],
queryFn: (): Promise<{ name: string }> => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: 'Susan' })
}, 1000)
})
}
})
</script>

<template>
<div v-if="isSuccess">
{{ data.name }}
</div>
</template>
Got:
src/components/Test2.vue:18:8 - error TS18048: '__VLS_ctx.data' is possibly 'undefined'.

18 {{ data.name }}
src/components/Test2.vue:18:8 - error TS18048: '__VLS_ctx.data' is possibly 'undefined'.

18 {{ data.name }}

Did you find this page helpful?