Skip to content

queryOptions should to pass initialData with a callback that is potentially returning undefined #7341

@ShacharHarshuv

Description

@ShacharHarshuv

Describe the bug

In angular-query
When using queryOptions '@tanstack/angular-query-experimental' and passing an initial value function, typescript will not allow that typescript to return undefined. The following code will not compile:

interface Todo {
  id: string;
  title: string;
}

export const todoQueryOption = (id: string | null) =>
  queryOptions({
    queryKey: ['todo', id],
    queryFn: () =>
      Promise.resolve({
        id: '1',
        title: 'Do Laundry',
      }),
    initialData: (): Todo | undefined => undefined,
  });

This should be allowed because I might want to check if I have this particular "todo" item in the cache, and if I don't, I would want angular query to request that item. Since this is conditional, I have to put it in a function that might either have a todo or not (in the example I set it to undefined just for the example).

I believe this has to do with this type definition:

export type DefinedInitialDataOptions<
  TQueryFnData = unknown,
  TError = DefaultError,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
  initialData:
    | NonUndefinedGuard<TQueryFnData>
    | (() => NonUndefinedGuard<TQueryFnData>)
}

Which should be changed to:

export type DefinedInitialDataOptions<
  TQueryFnData = unknown,
  TError = DefaultError,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
  initialData:
    | NonUndefinedGuard<TQueryFnData>
    | (InitialDataFunction<TQueryFnData>)
}

Your minimal, reproducible example

https://stackblitz.com/edit/stackblitz-starters-jdj53x?file=src%2Fmain.ts

Steps to reproduce

  1. Write this code in angular query:
interface Todo {
  id: string;
  title: string;
}

export const todoQueryOption = (id: string | null) =>
  queryOptions({
    queryKey: ['todo', id],
    queryFn: () =>
      Promise.resolve({
        id: '1',
        title: 'Do Laundry',
      }),
    initialData: (): Todo | undefined => undefined,
  });
  1. It wouldn't compile.

Expected behavior

The code should compile

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: Windows
  • Runtime: Node 20.11.0
  • (No browser is used to reproduce this bug)

Tanstack Query adapter

angular-query

TanStack Query version

5.32.0

TypeScript version

5.3.0

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions