← TypeScript

Advanced · 11 of 12 · 17 min read

Typing async code and errors

What Promise<T> and Awaited<T> actually guarantee, why a catch parameter is unknown, and how to type a result you are forced to handle.

  • async / await
  • Error handling

TypeScript types the value a promise resolves to and says nothing at all about what it rejects with. Everything awkward about typed error handling follows from that single asymmetry.

Promise<T> and async

async function getUser(id: number) {
  return { id, name: "Ana" };
}
// Inferred: Promise<{ id: number; name: string }>

async function getNothing(): Promise<void> {
  console.log("done");
}

const user = await getUser(1);
console.log(user.name, await getNothing());

An async function always returns a promise, and the annotation must say so — Promise<User>, never User. Returning a promise from inside an async function does not double-wrap it:

async function outer(): Promise<string> {
  return Promise.resolve("x");  // not Promise<Promise<string>>
}

console.log(await outer());

Awaited<T> is the type-level version of that flattening, and it recurses:

type A = Awaited<Promise<string>>;                  // string
type B = Awaited<Promise<Promise<number>>>;         // number
type C = Awaited<string>;                           // string — not a promise, passed through

declare function load(): Promise<{ id: number }>;
type Loaded = Awaited<ReturnType<typeof load>>;     // { id: number }

const loaded: Loaded = { id: 1 };
console.log(loaded.id);

Awaited<ReturnType<typeof fn>> is the idiom for “the thing this async function actually gives me”, and it is worth knowing because ReturnType alone stops at the promise.

The combinators

Each one has a different result type, and the differences are the whole reason to pick between them:

declare function getUser(): Promise<{ id: number }>;
declare function getPosts(): Promise<string[]>;

// all — a tuple, in order, inferred positionally
const [user, posts] = await Promise.all([getUser(), getPosts()]);
// user: { id: number }, posts: string[]

// allSettled — a tuple of result objects, nothing rejects
const settled = await Promise.allSettled([getUser(), getPosts()]);
if (settled[0].status === "fulfilled") console.log(settled[0].value.id);

// race / any — the union of the element types
const first = await Promise.race([getUser(), getPosts()]);

console.log(user.id, posts.length, first);

Promise.all on a tuple infers a tuple — each position keeps its own type, which is what makes the destructuring above work. On an array of one type it produces T[], as you would expect.

allSettled gives a discriminated union per element, and the discriminant is status:

declare const results: PromiseSettledResult<number>[];

for (const result of results) {
  if (result.status === "fulfilled") console.log(result.value.toFixed(0));
  else console.log(result.reason);  // `reason` is `any` — the untyped channel again
}
Combinator Resolves to Rejects when
Promise.all a tuple of the values the first rejection
Promise.allSettled a tuple of { status, value } / { status, reason } never
Promise.race the union of the values the first settled is a rejection
Promise.any the union of the values all reject, with an AggregateError

catch is unknown

async function run() {
  try {
    await Promise.reject(new Error("boom"));
  } catch (error) {
    // error: unknown — under `strict`
    // console.log(error.message);  // 'error' is of type 'unknown'

    if (error instanceof Error) console.log(error.message);
    else console.log("non-error thrown:", error);
  }
}

run();

This is correct rather than inconvenient: throw accepts any value, and plenty of real code throws strings, objects, or undefined. Before useUnknownInCatchVariables (TypeScript 4.4, part of strict) the parameter was any, and error.message on a thrown string compiled and produced undefined.

A reusable narrowing function is the usual answer:

function toError(value: unknown): Error {
  if (value instanceof Error) return value;
  if (typeof value === "string") return new Error(value);
  return new Error(JSON.stringify(value));
}

try {
  throw "a bare string";
} catch (error) {
  console.log(toError(error).message); // "a bare string"
}

Custom errors, narrowed by a discriminant

instanceof works on your own error classes, with one caveat and one alternative:

class HttpError extends Error {
  readonly kind = "http" as const;
  constructor(readonly status: number, message: string) {
    super(message);
    this.name = "HttpError";
    Object.setPrototypeOf(this, HttpError.prototype); // for ES5 targets
  }
}

class ValidationError extends Error {
  readonly kind = "validation" as const;
  constructor(readonly field: string) {
    super(`invalid ${field}`);
    this.name = "ValidationError";
  }
}

type AppError = HttpError | ValidationError;

function describe(error: AppError) {
  switch (error.kind) {
    case "http": return `HTTP ${error.status}`;
    case "validation": return `field ${error.field}`;
  }
}

console.log(describe(new HttpError(404, "not found")));
console.log(describe(new ValidationError("email")));

The kind discriminant does two jobs instanceof cannot: it survives a value that crossed a realm or a serialisation boundary, and it gives the switch exhaustiveness checking — add a third error class to AppError and describe stops compiling.

The setPrototypeOf line is only needed when targeting ES5, where extends of a built-in breaks the prototype chain and instanceof silently returns false. With a modern target it is unnecessary.

Errors as values

The alternative to throwing is returning, and it is the one place the type system can actually enforce handling:

type Result<T, E = Error> =
  | { ok: true; value: T }
  | { ok: false; error: E };

async function getUser(id: number): Promise<Result<{ id: number }, HttpError>> {
  try {
    if (id < 0) throw new HttpError(400, "bad id");
    return { ok: true, value: { id } };
  } catch (error) {
    return { ok: false, error: error instanceof HttpError ? error : new HttpError(500, "unknown") };
  }
}

declare class HttpError extends Error { constructor(status: number, message: string); status: number }

const result = await getUser(-1);
if (result.ok) console.log(result.value.id);
else console.log(result.error.status);  // typed, and impossible to skip

A throw is invisible in a signature: nothing tells a caller that a function can fail, and nothing complains when they do not handle it. A Result puts the failure in the return type, so the compiler forces the check — result.value does not exist until result.ok has been tested.

The cost is real: every caller unwraps, and it composes worse than await with a try/catch at the top. The usual split is to return Result at boundaries where failure is expected and routine — a parse, a validation, a lookup that can miss — and to throw for genuinely exceptional conditions that a top-level handler should catch.

Typing an async boundary properly

Putting it together for the most common real case:

interface ApiError { status: number; message: string }

async function fetchJson<T>(
  url: string,
  parse: (value: unknown) => T,
): Promise<Result<T, ApiError>> {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      return { ok: false, error: { status: response.status, message: response.statusText } };
    }
    return { ok: true, value: parse(await response.json()) };
  } catch (error) {
    return { ok: false, error: { status: 0, message: toError(error).message } };
  }
}

type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
declare function toError(value: unknown): Error;

const user = await fetchJson("/api/user", (value) => value as { id: number });
console.log(user.ok ? user.value.id : user.error.status);

Two things to notice. response.json() is Promise<any>, which is the biggest unchecked hole in most TypeScript applications — the parse callback is there to close it, and it also gives T an inference site so no caller writes a type argument. And the network failure and the HTTP failure are different things, both ending up in the same typed channel.

Common mistakes

Annotating an async function with the bare value type

Mistake. async function getUser(): User. Why it fails. An async function returns a promise; the annotation is an error, and the fix people reach for is removing the annotation entirely. What to do instead. Promise<User> — or let it be inferred, which is usually better.

error.message on a catch variable

Mistake. Reaching for .message straight away, or annotating the parameter as Error. Why it fails. The variable is unknown, and annotating it as anything but unknown or any is itself an error. Not everything thrown is an Error. What to do instead. instanceof Error, or a toError(value: unknown): Error helper used everywhere.

A forgotten await inside a try

Mistake. try { doAsync(); } catch { ... }. Why it fails. The promise is returned, not awaited, so the rejection happens after the try block has exited and becomes an unhandled rejection. The types do not complain, because an ignored promise is a valid expression statement. What to do instead. Turn on no-floating-promises in the linter — this is one of the few important async errors the type system alone will not catch.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

Awaited<T> unwraps a promise, and it keeps unwrapping.

What is Awaited<Promise<Promise<string>>>?

Code sample
type A = Awaited<Promise<Promise<string>>>;

A promise type says what it resolves to, and nothing at all about how it fails.

Why can the rejection reason not be typed here?

Code sample
function load(): Promise<User> {
  return Promise.reject(new NetworkError());
}

With strict on, the caught value is unknown and has to be checked before it is used.

Why does error.message fail to compile?

Code sample
try {
  risky();
} catch (error) {
  console.log(error.message);
}

How do you make a custom error class narrowable with instanceof?

Practise async / await and Error handling →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.