How to type an async Function in TypeScript

avatar

Borislav Hadzhiev

Wed Feb 16 20222 min read

Type an async Function in TypeScript #

To type an async function in TypeScript, set its return type to Promise<type>. Functions marked async are guaranteed to return a Promise even if you don't explicitly return a value, so the Promise generic should be used when specifying the function's return type.

index.ts
type GetNumber = (num: number) => Promise<number>; // ✅ Arrow function with Type const getNumber: GetNumber = async (num) => { const result = await Promise.resolve(num); return result; }; interface IGetNumber { (num: number): Promise<number>; } // ✅ Arrow function with Interface const getNumber2: IGetNumber = async (num) => { const result = await Promise.resolve(num); return result; }; // ✅ Arrow function inline const getNumber3 = async (num: number): Promise<number> => { const result = await Promise.resolve(num); return result; }; // ✅ Named function inline async function getNumber4(num: number): Promise<number> { const result = await Promise.resolve(num); return result; }

The examples in the code snippet show how to add type definitions to async functions.

The first two examples use a type and an interface to type the async function. The syntax is different, but the concept is the same - async functions always return a promise, which resolves with the return value of the async function.

If the async function throws an error, then it returns a Promise, which will be rejected with an exception thrown from the async function.

The type we passed to the Promise generic is the type of the value that the async function returns.

If the async function does not return a value, you should set the return type of the async function to be Promise<void>.

index.ts
async function logNumber(num: number): Promise<void> { await Promise.resolve(); console.log(num); }

If the async function throws an error, you should set its return type to Promise<never>.

index.ts
async function logNumber(num: number): Promise<never> { await Promise.resolve(); throw new Error('Something went wrong'); }

If you forget to set use the Promise generic when specifying the return type of an async function, you would get a clear error message.

index.ts
// ⛔️ Error: The return type of an async function or method // must be the global Promise<T> type. // Did you mean to write 'Promise<never>'? async function logNumber(num: number): never { await Promise.resolve(); throw new Error('Something went wrong'); }
The only thing to note when typing an async function is that it's return type will always be a promise, regardless if it returns a value, doesn't return a value or throws an error.

This is why you should always use the Promise generic when typing an async function's return value.

Use the search field on my Home Page to filter through my more than 1,000 articles.