Borislav Hadzhiev
Thu Feb 24 2022·2 min read
Photo by Robson Morgan
To declare a function with a promise return type, set the return type of the
function to a promise right after the function's parameter list, e.g.
function getPromise(): Promise<number> {}
. If the return type of the function
is not set, TypeScript will infer it.
// ✅ Named function function getPromise(): Promise<number> { return Promise.resolve(5); } // 👇️ Unwrap promise type if necessary // 👇️ type T = number type T = Awaited<ReturnType<typeof getPromise>>; // ✅ Named async function async function getPromise2(): Promise<number> { return 10; } // ✅ Arrow function const getPromise3 = (): Promise<string> => { return Promise.resolve('hello'); }; // ✅ Class method class A { async getPromise(): Promise<string> { return 'hello world'; } } // ✅ Using a type as Promise<Type> type Person = { name: string; age: number; }; async function getPromise4(): Promise<Person[]> { return [ { name: 'Tom', age: 30, }, ]; }
You can set the return type of a function right after its parameter list.
function getPromise(a: number): Promise<number> { return Promise.resolve(a); }
If you need to unwrap the type of the Promise from a function's return type, use the Awaited utility type.
function getPromise(a: number): Promise<number> { return Promise.resolve(a); } // 👇️ Unwrap promise type if necessary // 👇️ type T = number type T = Awaited<ReturnType<typeof getPromise>>;
The Awaited
utility type recursively unwraps a promise and returns its type.
// 👇️ type A = string type A = Awaited<Promise<string>>;
The examples above show how to set the return type of a function to a promise containing different values.
The advantage of setting the return type of the function explicitly is that the type checker would throw an error if you try to return a promise of a different type.
async function getPromise2(): Promise<number> { // ⛔️ Type 'string' is not assignable // to type 'number'.ts(2322) return 'hello'; }
If you don't explicitly set the return type of the function, TypeScript will infer it.
// 👇️ function getPromise2(): Promise<string> async function getPromise2() { return 'hello'; }
If your function returns a Promise that may contain different values, use a union to specify the function's return type.
async function getPromise2(): Promise<string | null> { if (Math.random() > 0.5) { return null; } return 'success'; }
The function above returns a Promise that contains a string
or a null
value.
If your function returns a Promise that unwraps to an array of objects, it's more readable to use a type or an interface.
type Person = { name: string; age: number; }; async function getPromise4(): Promise<Person[]> { return [ { name: 'Tom', age: 30, }, ]; }
The function above returns a Promise that contains an array of objects of type
Person
.