haunted icon indicating copy to clipboard operation
haunted copied to clipboard

Using useState with generic types

Open atoy40 opened this issue 3 years ago • 0 comments

Hello,

I'm trying to code a generic hooks, but the type returns by useState cause a problem. A simple example :

export function useGenericTest<T>(query: () => Promise<T>) {
  const [result, setResult] = useState<T>();

  useEffect(() => {
    query().then((value) => {
      setResult(value);
    });
  }, [query]);

  return result;
}

in the useEffect function, the value variable is of type T (because query function returns a Promise<T>) but the setResult function refuses to accept T type. This is because the setResult type is : StateUpdater<T extends (...args: any[]) => infer S ? S : T> But as P is generic, typescript cannot determine if is a function (and so use the infer type) or not.

May be I'm wrong somewhere ? btw, this kind of code has not problem with the react hook (it does not try to determine if the generic type pass to useState is a function or not)

Thks for help Anthony.

atoy40 avatar Mar 02 '23 16:03 atoy40