Back to library

🔷TypeScript Type Narrowing

Replace unsafe `as` casts with control-flow narrowing, discriminated unions, and type predicates — then build a type-safe API client that narrows responses by status code.

Applied14 drops~2-week path · 5–8 min/daytechnology

Phase 1Unions and Control Flow

Understand unions and control-flow narrowing basics

4 drops
  1. A union is a promise you haven't kept yet

    6 min

    A union is a promise you haven't kept yet

  2. The compiler reads your if-statements

    6 min

    The compiler reads your if-statements

  3. typeof only gets you halfway

    7 min

    typeof only gets you halfway

  4. The never type is your safety net

    7 min

    The never type is your safety net

Phase 2Replacing Casts with Guards

Replace casts with typeof, instanceof, and in checks

5 drops
  1. One shared property, zero ambiguity

    7 min

    One shared property, zero ambiguity

  2. Teach the compiler what you already know

    7 min

    Teach the compiler what you already know

  3. Assert once, narrow everything after

    7 min

    Assert once, narrow everything after

  4. filter(Boolean) lies — here's what works

    6 min

    filter(Boolean) lies — here's what works

  5. Your narrowed type forgets itself in callbacks

    7 min

    Your narrowed type forgets itself in callbacks

Phase 3Discriminated Unions and Predicates

Compare discriminated unions, predicates, and assertions

4 drops
  1. Your API returns three shapes — pick the safe one

    7 min

    Your API returns three shapes — pick the safe one

  2. Your validation layer is a hidden type boundary

    7 min

    Your validation layer is a hidden type boundary

  3. Guard at the gate or check at every door

    7 min

    Guard at the gate or check at every door

  4. The callback ate your type — and the fix is boring

    7 min

    The callback ate your type — and the fix is boring

Phase 4Type-Safe API Client

Build a type-safe API client narrowing by status

1 drop
  1. Build an API client that narrows by status code

    8 min

    Build an API client that narrows by status code

Frequently asked questions

What is a discriminated union in TypeScript?
This is covered in the “TypeScript Type Narrowing” learning path. Start with daily 5-minute micro-lessons that build from fundamentals to hands-on application.
When should I write a type predicate?
This is covered in the “TypeScript Type Narrowing” learning path. Start with daily 5-minute micro-lessons that build from fundamentals to hands-on application.
How does the never type help with exhaustiveness?
This is covered in the “TypeScript Type Narrowing” learning path. Start with daily 5-minute micro-lessons that build from fundamentals to hands-on application.
Why does my narrowed type widen inside a callback?
This is covered in the “TypeScript Type Narrowing” learning path. Start with daily 5-minute micro-lessons that build from fundamentals to hands-on application.