Tutorials / TypeScript: Beginner to Advanced / Union types and type narrowing

Union types and type narrowing

18 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

One of several types

Real data is often not one type. An id may be a string or a number. A function may return a result or null. A union type, written with |, says "this or that".

type ID = string | number;

let userId: ID = 42;
userId = "abc-123";
// userId = true;   // Error: boolean is not part of ID
console.log(userId);

The catch: with a union, you can only use what is common to every member. If id is string | number, you cannot call id.toUpperCase(), because a number has no such method. First you have to find out which one you have. That step is called narrowing.

Narrowing with typeof

function formatId(id: string | number): string {
  if (typeof id === "string") {
    return id.toUpperCase();      // here id is string
  }
  return id.toFixed(0).padStart(6, "0");  // here id is number
}

console.log(formatId("ab-12")); // AB-12
console.log(formatId(42));      // 000042

Inside the if, TypeScript knows id is a string. After the if block returns, it also knows id must be a number. The compiler follows the flow of your code. This is why we write ordinary JavaScript checks and get types for free.

Truthiness and null checks

With strict mode, null and undefined are separate types, so a value that might be missing is a union:

function shout(text: string | null | undefined): string {
  if (!text) {
    return "(nothing)";
  }
  return text.toUpperCase();   // text is string here
}

function length(text?: string): number {
  return text?.length ?? 0;     // optional chaining and nullish coalescing
}

console.log(shout(null), shout("hi"), length(), length("abc"));

Careful: !text is also true for the empty string. If an empty string is a legal value, check text === null || text === undefined, or use text == null.

Narrowing with in and instanceof

interface Cat { meow(): string }
interface Dog { bark(): string }

function speak(pet: Cat | Dog): string {
  if ("meow" in pet) {
    return pet.meow();
  }
  return pet.bark();
}

function formatError(e: unknown): string {
  if (e instanceof Error) {
    return e.message;
  }
  return String(e);
}

console.log(speak({ meow: () => "meow" }), formatError(new Error("boom")));

in checks whether a property exists. instanceof checks the class. The second function is something you will write often. In catch (e) blocks the error is unknown under strict settings, since anything can be thrown in JavaScript.

Discriminated unions

This is the most useful pattern in the lesson. Give each member of the union a common property with a literal value, a "tag". Checking the tag narrows the whole object.

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }
  | { kind: "rectangle"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    case "rectangle":
      return shape.width * shape.height;
  }
}

console.log(area({ kind: "circle", radius: 2 }).toFixed(2));        // 12.57
console.log(area({ kind: "rectangle", width: 3, height: 4 }));      // 12

In each case, TypeScript knows exactly which variant it is dealing with, so shape.radius is allowed only in the circle branch. This pattern is excellent for state that has distinct modes, like a request that is loading, succeeded or failed, and it replaces a pile of optional properties.

Exhaustive checks

What if someone adds { kind: "triangle" } to Shape later? We want the compiler to tell us every switch that now misses a case. Add a final check using never:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}

function perimeter(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return 2 * Math.PI * shape.radius;
    case "square":
      return 4 * shape.side;
    default:
      return assertNever(shape);
  }
}

console.log(perimeter({ kind: "square", side: 2 }));

If you add a new variant and forget to handle it, shape in the default branch is no longer never, and the compiler stops with an error right at that line. I consider this one of the best features of TypeScript.

Custom type guards

Sometimes the check is more complex than typeof. You can write a function whose return type is a type predicate, value is Type:

interface User {
  id: number;
  name: string;
}

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

const data: unknown = JSON.parse('{"id": 7, "name": "Ali"}');

if (isUser(data)) {
  console.log(data.name.toUpperCase());   // data is User here
} else {
  console.log("not a user");
}

The predicate is a promise that you make. If your function says value is User and the check is sloppy, TypeScript believes you anyway. So make the checks thorough. This is the right way to turn an unknown value, such as parsed JSON, into a typed one.

Unions of literals

A union of literal values is a lightweight alternative to enums. The next lesson covers it in detail:

type Direction = "up" | "down" | "left" | "right";

function move(direction: Direction): string {
  return `Moving ${direction}`;
}

console.log(move("up"));
// move("diagonal");  // Error

Common mistakes

  • Calling a member of only one type on the union. Narrow first.
  • **Assuming !value means "missing".** 0 and "" are also falsy.
  • **Using as where a check would do.** A cast hides the problem, and a guard solves it.
  • Optional fields instead of a discriminated union. A type with data?, error? and loading? allows impossible combinations. Use tagged variants.
  • Forgetting the exhaustive check. New variants then pass silently.
  • Writing a sloppy type guard. A predicate that returns true too easily gives you false safety.

Try it yourself

  1. Write double(value: string | number) that doubles a number and repeats a string twice.
  2. Create a discriminated union Result = { ok: true; value: number } | { ok: false; error: string } and write a function that prints either.
  3. Add a triangle variant to Shape and let the compiler show you where to update.
  4. Write a type guard isStringArray(value: unknown): value is string[].
typescript
function formatId(id: string | number): string {
  if (typeof id === "string") {
    return id.toUpperCase();      // here id is string
  }
  return id.toFixed(0).padStart(6, "0");  // here id is number
}

console.log(formatId("ab-12")); // AB-12
console.log(formatId(42));      // 000042

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account