TanStackT
TanStack8mo ago
7 replies
urgent-maroon

Weird type bug when using `queryOptions` with `useQueries`

If you have a type where the only required key is
name
, the types of results in the combine function seems to be wrong. Any ideas on why this is?

import { queryOptions, useQueries } from "@tanstack/react-query";

type BrokenType = {
  name: string;
};

const brokenOptions = queryOptions({
  queryKey: ["broken"],
  queryFn: () => new Promise<BrokenType>(() => {}),
});

type WorkingType = {
  notName: string;
};

const workingOptions = queryOptions({
  queryKey: ["working"],
  queryFn: () => new Promise<WorkingType>(() => {}),
});

function useWorkingQueries() {
  useQueries({
    queries: [brokenOptions],
    combine: (results) => {
      return {
        // result.data is incorrectly typed as `BrokenType` (not unioned with `undefined`)
        data: results.map((result) => result.data),
        // result.isPending is incorrectly typed as `false` (not `boolean`)
        pending: results.some((result) => result.isPending),
      };
    },
  });

  useQueries({
    queries: [workingOptions],
    combine: (results) => {
      return {
        // result.data is correctly typed as `WorkingType | undefined`
        data: results.map((result) => result.data),
        // result.isPending is correctly typed as `boolean`, not just `false`
        pending: results.some((result) => result.isPending),
      };
    },
  });
}
Was this page helpful?