TanStackT
TanStack10mo ago
6 replies
continuing-aqua

Type narrowing for hook that has multiple queries

Hey folks, I'm wondering if someone can help me figure this query/typescript issue out. For the useQuery hook it's well known that if you look for isPending and isError then you get some helpful type narrowing on the data.

My question is how to create a hook that wraps multiple useQueries and returns type narrowing for all the returned data.

Here's a stripped down version of the hook

const useSomeData = () => {
  const q1 = useQuery1() // A wrapper hook that returns useQuery()

  const q2 = useQuery2() // // A wrapper hook that returns useQuery()

  const q3 = useQuery3() // A wrapper hook that returns useQuery()

  const isPending =
    q1.isPending ||
    q2.isPending ||
    q3.isPending;

  const isError =
    q1.isError ||
    q2.isError ||
    q3.isError;

  return {
    isError,
    isPending,
    q1,
    q2,
    q3,
  };
};


I'd like to be able to do use this hook like the following:

const [q1,q2,q3,isPending,isError] = useSomeData()

if (!isError || !isPending) {
  console.log(q1.data.someProperty) // Type error
}


Without there being a type error. I think we can be certain that data exists at the point of the log statement, right? So how can I structure my hook to have proper type narrowing?
Was this page helpful?