TExcelTAD
Home › TypeScript › TS Async TypeScript

Async TypeScript

JavaScript does slow work — network requests, timers, file access — asynchronously: a function starts the work and returns a Promise that settles later. TypeScript tracks what each promise will eventually hold, so you get the same type safety for async code as for ordinary code.

The Promise<T> type

A Promise<T> is a promise that resolves with a value of type T. An async function always returns a promise, so its return type is written Promise<…>:

ts · try it yourself
function wait(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function fetchPrice(product: string): Promise<number> {
  await wait(10);                 // pretend this is a network call
  return product.length * 1.5;
}

const price = await fetchPrice("coffee");
console.log(price.toFixed(2));

export {};
9.00

Top-level await works because the file is a module (note the export {}).

Forgetting the await is one of the most common async bugs. TypeScript catches it, because a Promise<number> is not a number:

ts · try it yourself
async function fetchPrice(product: string): Promise<number> {
  return product.length * 1.5;
}

async function main() {
  const price = fetchPrice("tea");
  console.log(price.toFixed(2));
}
main();
main.ts(7,21): error TS2339: Property 'toFixed' does not exist on type 'Promise<number>'.

And if a function is declared async, its return type must be a promise:

ts · try it yourself
async function total(a: number, b: number): number {
  return a + b;
}
main.ts(1,45): 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>'?

Running tasks in parallel

await in a loop runs tasks one after another. When tasks are independent, start them all and wait with Promise.all. TypeScript infers a tuple of the result types, in order:

ts · try it yourself
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

async function getUser(id: number) {
  await wait(30);
  return { id, nickname: `user${id}` };
}

async function getOrderCount(id: number) {
  await wait(10);
  return id * 3;
}

// type: [{ id: number; nickname: string }, number]
const [user, orders] = await Promise.all([getUser(7), getOrderCount(7)]);
console.log(`${user.nickname} has ${orders} orders`);

export {};
user7 has 21 orders
Helper Resolves when Result type
Promise.all([a, b]) all fulfil (rejects on the first failure) [A, B]
Promise.allSettled([a, b]) all have settled [PromiseSettledResult<A>, PromiseSettledResult<B>]
Promise.race([a, b]) the first one settles A | B
Promise.any([a, b]) the first one fulfils A | B

Handling failures

A rejected promise throws at the await. As with synchronous code, the error in catch has type unknown in strict mode, so check it before using it. Promise.allSettled is handy when you want every result, successes and failures alike — and its result type is a discriminated union you can narrow on status:

ts · try it yourself
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));

async function loadReport(id: number): Promise<string> {
  await wait(id * 5);
  if (id === 2) throw new Error(`report ${id} not found`);
  return `report ${id}: OK`;
}

try {
  await loadReport(2);
} catch (err) {
  console.log("caught:", err instanceof Error ? err.message : err);
}

const results = await Promise.allSettled([1, 2, 3].map(loadReport));
for (const r of results) {
  if (r.status === "fulfilled") console.log("✔", r.value);
  else console.log("✘", (r.reason as Error).message);
}

export {};
caught: report 2 not found
✔ report 1: OK
✘ report 2 not found
✔ report 3: OK

Typing callbacks and generic async helpers

Generics make reusable async utilities type-safe. This withTimeout helper keeps the type of whatever promise you give it, and Awaited<T> gives you the unwrapped type of a promise:

ts · try it yourself
function withTimeout<T>(task: Promise<T>, ms: number): Promise<T> {
  const timer = new Promise<never>((_, reject) =>
    setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms)
  );
  return Promise.race([task, timer]);
}

const slow = new Promise<string>((r) => setTimeout(() => r("done"), 50));
const fast = new Promise<number>((r) => setTimeout(() => r(42), 5));

type FastResult = Awaited<typeof fast>;   // number
const n: FastResult = await withTimeout(fast, 20);
console.log(n);

try {
  await withTimeout(slow, 20);
} catch (err) {
  console.log((err as Error).message);
}

export {};
42
timed out after 20 ms

Tip: The return type Promise<never> for the timer says "this promise never resolves with a value — it can only reject". never disappears in the union, so Promise.race still returns Promise<T>.

Note: Turn on the ESLint rule @typescript-eslint/no-floating-promises in real projects. It reports promises you forgot to await or handle, which the compiler alone can't always detect.

Test yourself

What is the return type of async function f() { return "hi"; }?

  1. string
  2. Promise<string>
  3. Promise<void>
  4. Awaited<string>

What type does await Promise.all([getName(), getAge()]) have if they return Promise<string> and Promise<number>?

  1. (string | number)[]
  2. [string, number]
  3. Promise<[string, number]>
  4. any[]

What does Awaited<Promise<Promise<boolean>>> evaluate to?

  1. Promise<boolean>
  2. boolean
  3. unknown
  4. never