matthewp / haunted

React's Hooks API implemented for web components 👻
BSD 2-Clause "Simplified" License
2.6k stars 92 forks source link

Using useState with generic types #466

Open atoy40 opened 1 year ago

atoy40 commented 1 year ago

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.