Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 96 ยท Async and Errors

Promises and async/await

Type asynchronous TypeScript code: Promise<T>, async return types, Awaited, typing Promise.all, allSettled, race and any, async callbacks and async iterators.

Almost every real program waits for something: a file, a database, a timer, a network response. JavaScript models "a value that will arrive later" with a promise, and async/await lets you write code that waits for promises as if it were ordinary step-by-step code. If those ideas are new, start with the JavaScript lessons on promises and async/await; this lesson assumes you know how they behave and focuses on their types.

TypeScript describes a promise with the generic type Promise<T>, where T is the value it eventually produces. Once you can read that type, the rest follows: async functions always return Promise<T>, await unwraps it, Awaited<T> unwraps it at the type level, and the combinators like Promise.all compute precise result types for you. You'll also see the two classic async mistakes that types catch (a forgotten await and an unhandled rejection) and one they don't.

Promise types and async functions

An async function always returns a promise, even if its body returns a plain value. TypeScript reflects this: if the body returns T, the function's return type is Promise<T>. Using await on a Promise<T> gives you back a T.

This lesson proves types with two tiny helpers you may remember from utility types: Equal<A, B> is true only when two types are identical, and Expect<T> only accepts true. A line like type _t = Expect<Equal<X, Y>>; therefore compiles only if X and Y are the same type, so if the program runs at all, every check passed.

TypeScript What async functions return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program prints true { id: 1, name: 'Ada' } 2. Our editor runs main.ts as an ES module, so top-level await works, as in the lines above. In older CommonJS projects, you'd wrap the code in an async function main() and call it.

Annotating the return type of an exported async function is a good habit. It documents the contract, and it catches mistakes inside the body: returning a string from a function declared Promise<User> is an error at the return, not somewhere far away at a caller.

The mistakes types catch

The most common async bug is forgetting await. In JavaScript you'd get undefined from reading a property of a promise, and the bug surfaces later. In TypeScript, a Promise<User> simply has no name property. The second mistake is annotating an async function with a non-promise type. This example fails on purpose with both:

TypeScript Forgotten await and a wrong return type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(10,18): error TS2339: Property 'name' does not exist on type 'Promise<User>'.
main.ts(12,29): error TS1064: The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<number>'?

When you see "does not exist on type Promise<...>", the fix is nearly always a missing await. The TS1064 message even suggests the fix: write Promise<number>.

One forgotten await is not a type error: calling an async function as a statement and ignoring its promise, like saveUser(user);. The code compiles, the save runs in the background, and if it fails, the rejection goes unhandled (Node prints an error and exits). The typescript-eslint rule no-floating-promises reports these. Either await the call, return the promise, or mark it as intentionally ignored with void saveUser(user); and attach a .catch.

Creating promises with new Promise

When you wrap a callback API in new Promise, TypeScript can't guess what you'll pass to resolve later, so it infers Promise<unknown>. Give the constructor a type argument instead. Generic helpers like delay and withTimeout then carry types through automatically (generics explains the <T> syntax):

TypeScript Typed promise helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

resolve is typed from the type argument, so resolve('seven') inside delay<number> would be an error. reject accepts anything, because JavaScript lets you reject with any value. That is why the rejection reason and the catch variable are never typed for you, a point the next lesson, Error handling, takes up in detail.

Promise.withResolvers() (ES2024, Node 22+) returns { promise, resolve, reject }. It's handy when the code that settles a promise lives somewhere other than the code that creates it, such as an event handler or a queue.

Unwrapping types with Awaited

await unwraps promises at runtime; Awaited<T> does the same for types. It unwraps recursively, the same way await flattens nested promises, and leaves non-promise types unchanged. Combined with ReturnType, it gives you "what this async function eventually produces" without writing the type twice:

TypeScript Awaited and ReturnType together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Awaited also handles "thenables" (any object with a promise-like then method), which is how TypeScript types await itself. You'll rarely write it in application code outside Awaited<ReturnType<...>>, but it shows up constantly in library signatures, including the combinators below.

Typing Promise.all, allSettled, race and any

The static Promise methods (covered at runtime in promise combinators) have carefully written types. The best one to know is Promise.all: give it an array literal of different promises and you get back a tuple with each element's own type, in order, so destructuring just works:

TypeScript Typed Promise.all and allSettled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The results show how each method is typed:

Method Result type for inputs Promise<A>, Promise<B> Rejects when
Promise.all Promise<[A, B]> (array input: Promise<A[]>) any input rejects
Promise.allSettled Promise<[PromiseSettledResult<A>, PromiseSettledResult<B>]> never
Promise.race Promise<A | B> the first input to settle rejects
Promise.any Promise<A | B> all inputs reject (with an AggregateError)

PromiseSettledResult<T> is a discriminated union of { status: 'fulfilled'; value: T } and { status: 'rejected'; reason: any }. Checking result.status narrows it, exactly as in the loop above.

The tuple typing only works when TypeScript sees the elements individually, like an array literal written in the call. If you pass a variable of type Promise<number>[], you get number[], which is all TypeScript can know about an array of unknown length.

Async callbacks: map, forEach and void

Callbacks are where async code goes wrong most often. array.map(async ...) gives you an array of promises, which you usually feed to Promise.all. forEach with an async callback compiles fine but doesn't wait for anything, because forEach ignores what the callback returns:

TypeScript Sequential, parallel and the forEach trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows all three behaviors. The parallel run finishes in the order saved 3, saved 2, saved 1, yet values stays [ 10, 20, 30 ], because Promise.all keeps input order. The sequential loop saves in order. After forEach, 0 saves have finished; they complete in the background later.

Why doesn't TypeScript stop the forEach version? The callback type of forEach returns void, and a function returning something can always be used where a void-returning function is expected. That rule is useful (it lets arr.forEach((x) => list.push(x)) compile), but it means async callbacks slip through. Use for...of with await for sequential work, and map plus Promise.all for parallel work.

Async iterables and for await

Some data arrives as a stream of values over time: lines of a file, pages of an API, messages from a queue. An async generator function (async function*) produces such a stream, and for await...of consumes it. The types are AsyncGenerator<T, TReturn, TNext> for the generator object and AsyncIterable<T> for "anything you can for await over":

TypeScript Typing an async generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Typing parameters as AsyncIterable<T> keeps functions flexible: Node streams, readline interfaces and your own generators all satisfy it. The Iterators and Generators lesson explains the three type parameters of Generator and AsyncGenerator and how the sync and async versions relate.

When reading a type such as Promise<Result<User[], ApiError>>, peel it from the outside in: "a promise that eventually gives a result, which is either a list of users or an API error." Async types are mostly ordinary types wrapped in one layer of Promise.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of count in async function f() { return 5; } const count = f();?

    An async function always returns a promise. Without await, count is the promise itself, so its type is Promise of number.
  2. 2. What is the type of pair in const pair = await Promise.all([loadName(), loadAge()]); if they return Promise<string> and Promise<number>?

    For an array literal of promises, Promise.all resolves to a tuple with each element's own type in order, and await unwraps the outer promise.
  3. 3. Why does new Promise((resolve) => resolve(5)) produce a weak type?

    TypeScript cannot know what you will pass to resolve when the constructor is called, so the type argument defaults to unknown. Pass it explicitly.
  4. 4. Does ids.forEach(async (id) => { await save(id); }); compile, and does it wait for the saves?

    The forEach callback returns void, and any function may be used as a void callback. The promises are created and dropped, so code after forEach runs before the saves finish.
  5. 5. What is Awaited<Promise<Promise<boolean>>>?

    Awaited unwraps recursively, just like await flattens nested promises at runtime.

Summary

  • Promise<T> is a value of type T that arrives later. An async function returning T has the return type Promise<T>, and await turns Promise<T> back into T.
  • A missing await usually shows up as Property 'x' does not exist on type 'Promise<...>'. An unawaited statement call compiles, so use no-floating-promises to catch it.
  • Annotate async return types as Promise<T> (TS1064 otherwise), and give new Promise<T> a type argument instead of accepting Promise<unknown>.
  • Awaited<T> unwraps promises recursively at the type level; Awaited<ReturnType<typeof fn>> names what an async function produces.
  • Promise.all on an array literal returns a typed tuple; allSettled returns PromiseSettledResult<T> items you narrow by status; race and any return a union.
  • Rejection reasons are untyped (any); treat them as unknown.
  • Use for...of with await for sequential work and map + Promise.all for parallel work. forEach with an async callback waits for nothing.
  • async function* produces an AsyncGenerator<T, R, N>; accept streams as AsyncIterable<T> and consume them with for await.

Next: Error Handling