简体   繁体   中英

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> 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

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>] [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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM