vendredi 19 mars 2021

How can I get return type of generic functions?

I tried to create context that stores return value of useState in Typescript like below:

const SomethingContext = React.createContext<ReturnType<typeof useState<Something>> | undefined>(undefined);

But it throws a syntax error because of <Something> type specification.

If I use ReturnType without type specification, SomethingContext becomes React.Context<[unknown, React.Dispatch<unknown>] | undefined>, which I didn't expected because of unknown.

What did I went wrong?

And more in general, how can I get the return type of generic functions with type specified?

Expected behavior

A type GenericReturnType which satisfies:

GenericReturnType<Something, useState> gives [Something | undefined, React.Dispatch<Something>]




Aucun commentaire:

Enregistrer un commentaire