TypeScript in Practice

Everyday types · Lesson 4 of 12 · 16 min

Unions and narrowing

A union says "this value is one of these". Narrowing is how you find out which one, and TypeScript follows along.

type Result = { ok: true; data: string[] } | { ok: false; error: string };
 
function render(result: Result) {
  if (result.ok) {
    return result.data.join(", "); // data exists here
  }
  return `Failed: ${result.error}`; // and error exists here
}

The ok property is a discriminant: a field with a literal type that's different in each member. It's the most useful pattern in this course.

Ways to narrow

CheckNarrows
typeof x === "string"primitives
Array.isArray(x)arrays
"email" in userobjects with a property
x instanceof Dateclasses
result.okdiscriminated unions

Make TypeScript check you covered every case

type Status = "draft" | "sent" | "paid";
 
function label(status: Status) {
  switch (status) {
    case "draft": return "Draft";
    case "sent": return "Sent";
    case "paid": return "Paid";
    default:
      const never: never = status; // errors if you add a status and forget it here
      return never;
  }
}

Exercise: add "void" to Status and watch the compiler point at every switch you need to update.