Skip to content

Type Guards and Narrowing

Medium ~35 min

What you'll build

A set of type guards for a discriminated union of API response types, plus a generic isDefined guard that removes null/undefined.

Goals

  • Write user-defined type guards (x is T)
  • Use discriminated unions for exhaustive checking
  • Narrow with the 'in' operator
  • Build a generic filter that removes nulls

Prerequisites

  • Union types
  • Functions with type predicates
  • Array filter method

Steps

  1. 1

    Define a discriminated union

    Create a union of API response types with a 'status' discriminant: Success, Error, Loading. The discriminant lets the compiler narrow in switch statements.

    Code
    type ApiResponse<T> =
      | { status: 'success'; data: T; }
      | { status: 'error'; message: string; }
      | { status: 'loading' };
    
    function handleResponse<T>(res: ApiResponse<T>) {
      switch (res.status) {
        case 'success': return res.data;      // T — narrowed
        case 'error':   return res.message;   // string — narrowed
        case 'loading': return 'Loading...';  // narrowed
      }
    }

    Expected result

    Each case branch narrows res to the correct variant — no casting needed.

  2. 2

    Write a custom type guard

    A type guard is a function returning 'x is T'. Write isError that checks if a value is an Error instance, and the compiler will narrow after the check.

    Code
    function isError(x: unknown): x is Error {
      return x instanceof Error;
    }
    
    try {
      // ... risky code
    } catch (e: unknown) {
      if (isError(e)) {
        console.log(e.message);  // OK — narrowed to Error
      } else {
        console.log(String(e));
      }
    }

    Expected result

    After isError(e), e is narrowed to Error and .message is accessible.

  3. 3

    Narrow with the 'in' operator

    The 'in' operator narrows based on property presence. Write a guard that distinguishes two types by a unique property.

  4. 4

    Build isDefined and filterDefined

    Write a generic isDefined<T>(x: T | null | undefined): x is T guard, and a filterDefined function that removes nulls from an array. The return type should not include null.

  5. 5

    Test exhaustive checking

    Add a new variant to ApiResponse and observe the compiler error in handleResponse — exhaustive checking catches missing cases. This is a key safety benefit of discriminated unions.

    Code
    // Add | { status: 'cancelled' } to ApiResponse
    // The switch in handleResponse now has a type error:
    // 'Not all code paths return a value'
    // This forces you to handle the new case.

    Expected result

    Adding a variant causes a compile error until you handle it — exhaustiveness.

Try it yourself

What you learned

You mastered type narrowing — the feature that makes TypeScript feel like a static language while keeping JavaScript's runtime flexibility. Discriminated unions enable exhaustive, safe handling.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic