Borislav Hadzhiev
Wed Feb 16 2022·2 min read
Photo by Kinga Cichewicz
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.
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.
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>
.
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>
.
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.
// ⛔️ 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'); }
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.