Search code examples
javascripttypescript

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


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}


Solution

  • 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