안재원
안재원

Reputation: 31

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, React.Dispatch<Something>]

Related question

Typescript ReturnType of generic function

Upvotes: 3

Views: 609

Answers (1)

zixiCat
zixiCat

Reputation: 1059

First, useState is not a type at all, It cannot be passed in the way of generic, thus, it's not realistic to GenericReturnType<Something, useState> into [Something | undefined, React.Dispatch<Something>]

Second, the type of useState<T>() is equal to [T, React.Dispatch<React.SetStateAction<T>>], I am curious why you do not use React.Dispatch<React.SetStateAction<T> directly instead?

Upvotes: 1

Related Questions