Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the return type of async function in typescript? [duplicate]

Consider we have a function like below

const upper = (str: string) : string => string.toUpperCase() 

We can get the type of the function using ReturnType

type Test = ReturnType<typeof upper>

But now consider we have an async function.

const getUserData = async (uid: string): Promise<{name: string, email: string}> => {
   ...
};

Now how could we get that type {name: string, email: string}

like image 310
Maheer Ali Avatar asked Jan 25 '23 10:01

Maheer Ali


1 Answers

You can create AsyncReturnType with infer:

type AsyncReturnType<T extends (...args: any) => Promise<any>> =
    T extends (...args: any) => Promise<infer R> ? R : any

Test:

const getUserData = async (uid: string): Promise<{ name: string, email: string }> => {...};

type T1 = AsyncReturnType<typeof getUserData> // { name: string; email: string; }

Sample

like image 194
ford04 Avatar answered Jan 29 '23 20:01

ford04