Skip to content

narrowing typescript keeps data as possible undefined #9244

Open
@Tbaile

Description

@Tbaile

Describe the bug

Hello,
I'm using query to fetch some data coming from the server using Vue, the code looks like this:

const { error, data, status } = useQuery({
    queryKey: ['units', page],
    queryFn: () => axios.get<PaginatedResponse<Unit>>('/api/units?page=' + page.value),
    select: (response) => response.data,
    placeholderData: keepPreviousData,
})

per docs, if status == success or isSuccess is true, we should have data defined with type from the calling queryFn. However it appears by @tanstack/query-core type definition that this is not the case:

interface SuccessAction<TData> {
  data: TData | undefined
  type: 'success'
  dataUpdatedAt?: number
  manual?: boolean
}

Is this wanted due to uncertainty of the data being returned? If that so, shouldn't this be responsibility of the type definition of the called queryFn?

Your minimal, reproducible example

https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgVwM4FMCKz1QJ5wC+cAZlBCHAOQACMAhgHaoMDGA1gPQBuOAtAEcc+KgFgAUBImsIzeEgAm9BgBo4wVAGVkrVulSoicALwoM2XHgAUCCXHtwhlgGKMAXHCsBKEwD44AArkIBroAHRQ+hAANtzoVgCsXip2Dk74ANLoeB4A2lQw+jBUALoShF5S4sAknhrauvqoPrbiDnBKDBKcnPYAegD85RJAA

Steps to reproduce

Simply check in typescript playground, data is of type Ref<number, number> | Ref<undefined, undefined> even when resolved and inside a if check for success

Expected behavior

Per doc, this shouldn't be allowed

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

Issue is platform agnostic

Tanstack Query adapter

vue-query

TanStack Query version

v5.76.0

TypeScript version

5.8.3

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions