Skip to lesson

TypeScript · Lesson 36 of 42

Typing promises and async functions

Type asynchronous code with Promise<T>, async and await, run promises in parallel with Promise.all, and avoid the classic mistakes of a missing await.

Beginner to advanced·15 min·Modules, async code and tooling·Updated 2026-11-24

UNDERSTAND IT. THEN TRY IT.

What you can do after this lesson

You will type asynchronous code correctly: functions that return promises, async and await, and running several operations at once. Almost every real program waits for something, such as a file, a network request or a timer, so this lesson ties TypeScript to how modern JavaScript really works.

Promise

A promise stands for a value that will arrive later. Its type says what the value will be: Promise<number> will eventually produce a number. Here is a helper that waits, which this lesson reuses:

typescript
function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

function getNumber(): Promise<number> {
  return new Promise(resolve => setTimeout(() => resolve(42), 10));
}

getNumber().then(n => console.log(n + 1));
result
43

Promise<void> means "completes later, with no useful value". In .then(n => ...), n is a number, because the compiler follows the promise's type argument.

async and await

An async function always returns a promise, so you annotate the result as Promise<T>, where T is the type of the value you return:

typescript
function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function fetchPrice(item: string): Promise<number> {
  await delay(10);
  return item === "pen" ? 2.5 : 9.99;
}

async function main(): Promise<void> {
  const price = await fetchPrice("pen");
  console.log(price.toFixed(2));
}

main();
result
2.50

Inside main, await fetchPrice("pen") unwraps Promise<number> to a plain number, so toFixed works. If the function returned a string, the Promise<number> annotation would reject it, exactly like any return type.

The classic mistake: missing await

If you forget await, you are left holding the promise itself. TypeScript catches this in most places:

typescript
async function fetchPrice(): Promise<number> {
  return 2.5;
}

async function main() {
  const price: number = fetchPrice();
  console.log(price);
}
result
example.ts(6,9): error TS2322: Type 'Promise<number>' is not assignable to type 'number'.

The same idea applies to conditions: if (isValid()) with an async function is always true because a promise is truthy, which a type-aware linter (a later lesson) can flag. Using await outside an async function is also an error:

typescript
async function fetchPrice(): Promise<number> {
  return 2.5;
}

function main() {
  const price = await fetchPrice();
}
result
example.ts(6,17): error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.

Running things in parallel

Awaiting operations one after another makes them run in sequence. When they do not depend on each other, start them together with Promise.all, which waits for all and returns the results in order. TypeScript keeps each result's own type:

typescript
function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function getCount(): Promise<number> {
  await delay(20);
  return 3;
}

async function getName(): Promise<string> {
  await delay(10);
  return "Asha";
}

async function main(): Promise<void> {
  const [count, name] = await Promise.all([getCount(), getName()]);
  console.log(`${name} has ${count.toFixed(1)}`);
}

main();
result
Asha has 3.0

count is a number and name is a string, because the result is the tuple [number, string]. If one promise rejects, Promise.all rejects immediately. When you need every outcome even if some fail, use Promise.allSettled, whose results are a union describing success or failure:

typescript
async function main(): Promise<void> {
  const results = await Promise.allSettled([
    Promise.resolve(1),
    Promise.reject(new Error("failed")),
  ]);

  for (const result of results) {
    if (result.status === "fulfilled") {
      console.log("ok", result.value);
    } else {
      console.log("failed", (result.reason as Error).message);
    }
  }
}

main();
result
ok 1
failed failed

Each result is a discriminated union with status as its tag, so narrowing works exactly as in the earlier lesson.

Errors in async code

A rejected promise throws at the await, so use try and catch as with ordinary code. The next lesson covers how to type the caught error safely. A function that may fail can also return a result type, as the discriminated unions lesson showed, instead of throwing.

Awaited

The utility type Awaited<T> computes what you get after await, unwrapping nested promises. Combine it with ReturnType to name the result of an async function without repeating it:

typescript
async function loadUser() {
  return { id: 1, name: "Asha" };
}

type User = Awaited<ReturnType<typeof loadUser>>;

const user: User = { id: 2, name: "Ben" };
console.log(user);
result
{ id: 2, name: 'Ben' }

Common mistakes

Forgetting await. You get a promise where you expected a value. Annotating the variable usually makes the compiler catch it.

Awaiting in a loop when the work is independent. Use Promise.all to run things together.

Writing Promise but returning a value. The annotation must match what the function returns.

Using async without await. The function still returns a promise, which may not be what you intended.

Leaving promises unhandled. A promise you never await can fail silently. Linting rules (a later lesson) can catch these.

Exercise

Write async function fetchUser(id: number): Promise<{ id: number; name: string }> that waits briefly and returns a user. Write async function fetchAll(ids: number[]) that uses Promise.all with map to fetch every user at once. Then write one version that forgets an await and read the error. Finally, derive the user type with Awaited and ReturnType.

Next: Handling errors safely with unknown.

KNOWLEDGE CHECK

A quick check. You’ve got this.

Try each question. Every answer comes with an explanation.

0 / 4 understood
01 What is the return type of async function load(): Promise<number>?
02 What type does await give for an expression of type Promise<string>?
03 What does Promise.all([getNumber(), getString()]) resolve to?
04 What happens when you forget await and assign an async result to a number variable?

Ready for the next small win?

Mark the lesson complete when you are ready.

Course navigation

Frontend

TypeScript tutorial

Add types to JavaScript to catch mistakes before your code runs, from your first annotation to generics and real projects.

Your progress 0/42
Learning something new?Explore all courses