Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using useState with generic types #466

Open
atoy40 opened this issue Mar 2, 2023 · 0 comments
Open

Using useState with generic types #466

atoy40 opened this issue Mar 2, 2023 · 0 comments

Comments

@atoy40
Copy link

atoy40 commented Mar 2, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant