Home > front end >  typescript: react-query useQuery data after reassigning type narrowing doesnt work
typescript: react-query useQuery data after reassigning type narrowing doesnt work

Time:10-24

In react-query, data value of useQuery result is T | undefined. if I narrow down the type, it works. However, if I reassign it to a different variable, type narrowing stops working. It only happens when the reassigned data is referred inside callbacks, seems like. What is the issue here?

  const { data } = useQuery<number[]>("test", () => [1, 2, 3, 4]);

  let data2 = data;
  // filtering and sorting data here...

  const fun0 = () => {
    if (!data) return;

    //No error
    [1, 2, 3].map((one) => data[0]);
  };

  const fun = () => {
    if (!data2) return;

    //This works
    const foo = data2[0];

    //Type error here. data2 is still number[] | undefined ???
    [1, 2, 3].map((one) => data2[0]);
  };

You can see an example sandbox (Updated: With solution)

CodePudding user response:

The issue here is not the re-assignment but rather that data is const and data2 is let. This will also reproduce the issue:

const data = null! as number[] | undefined

let data2 = null! as number[] | undefined

Generally, when you are using let variables and narrow them, this information is not available inside of callbacks. After all, it is not known to the compiler if the variable was changed before the callback is executed. const variables can not be reassigned, so the value should theoretically not change (if the variable is some kind of nested object, you could modify the nested properties even if the variable is declared as const. But the compiler is smart enough to differentiate those scenarios. See this example)

See here or for a more in-depth-read here.


Playground

  • Related