TypeScript in Practice

TypeScript in real projects · Lesson 9 of 12 · 12 min

Errors you can't forget to handle

try/catch gives you an unknown error and no reminder that a function can fail. Returning errors as values makes failure part of the type.

type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };
 
async function createInvoice(input: NewInvoice): Promise<Result<Invoice, "LIMIT_REACHED" | "INVALID">> {
  if (await overLimit()) return { ok: false, error: "LIMIT_REACHED" };
  // …
  return { ok: true, value: invoice };
}

The caller can't use value without checking ok first:

const result = await createInvoice(input);
if (!result.ok) {
  return toast.error(messages[result.error]);
}
redirect(`/invoices/${result.value.id}`);

When to throw anyway

Throw for bugs and situations the caller can't handle (a missing environment variable, a corrupted file). Return errors for things the user can fix (validation, limits, permissions).

Catch blocks receive unknown. Narrow it with error instanceof Error before reading .message.