3. TypeScript Fundamentals & Type Thinking

Interfaces, type Aliases, Discriminated Unions & Narrowing

Model complex UI and API states cleanly in TypeScript: compare interface vs type, prevent impossible states with Discriminated Unions, and verify exhaustiveness using never.

3 min readUpdated 2026-12-01
In This Lesson
  • Choose cleanly between interface and type aliases
  • Eliminate impossible boolean-flag states using Discriminated Unions
  • Narrow unions safely using typeof, in, custom type predicates, and exhaustive never checks

Imagine modeling an async API fetch in React/TypeScript using three separate booleans:

ts
// BAD: allows impossible states like isLoading: true AND error: "Failed" AND data: [...]!
interface BadFetchState {
  isLoading: boolean;
  error?: string;
  data?: string[];
}

TypeScript lets you make impossible states unrepresentable using Discriminated Unions!

1. Interactive Narrowing Trace: Discriminated Unions

Give every variant in a union a shared literal tag property (commonly status, kind, or type):

ts
type ApiState =
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

Click through the stepper below to watch how TypeScript narrows ApiState inside each if / switch branch:

Interactive Walkthrough: Discriminated Union Type NarrowingStep 1 / 4
state: ApiState
Inferred Type: { status: 'loading' } | { status: 'success'; data: string[] } | { status: 'error'; message: string }

Step 1: Entry — Full Discriminated Union

Before checking `state.status`, TypeScript only lets you read shared properties (`state.status`), blocking `state.data` or `state.message`.

Exhaustiveness Checking with never

In a switch (state.status), add a default: branch assigning const _exhaustive: never = state;. If a teammate later adds { status: "idle" } to ApiState and forgets to update your switch, TypeScript immediately fails the build at compile time!

2. interface vs type: Which Should You Use?

Featureinterfacetype
Object shapes & class contracts (implements)GreatGreat
Union types ("idle" | "loading") & tuplesNoRequired
Mapped / Utility types (Partial, Omit)LimitedRequired
Extendinginterface Admin extends User {}type Admin = User & { role: "admin" }

Team rule of thumb: Use interface for extensible object/class contracts (or type consistently everywhere), and always use type for unions, tuples, and utility compositions.

3. Type Narrowing Tools & Custom Type Predicates

TypeScript tracks control flow across:

  • typeof x === "string" (primitives)
  • Array.isArray(x) (arrays)
  • "message" in err (checking property existence on objects)
  • Custom Type Predicate (x is User):
    ts
    interface User { id: number; name: string }
    function isUser(val: unknown): val is User {
      return typeof val === "object" && val !== null && "id" in val && "name" in val;
    }

Try It Yourself in the Playground

Run a clean state-machine renderer matching TypeScript's Discriminated Union + exhaustive switch pattern live in JavaScript:

JavaScriptTry It Live: Discriminated Union State Renderer
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Rewrite { isOpen: boolean; items?: string[]; errorMsg?: string } into a clean 3-state Discriminated Union type ModalState using kind: "closed" | "ready" | "failed".

Quick Checkpoints

Check Your Understanding

Why are Discriminated Unions ({ status: 'loading' } | { status: 'success'; data: T }) better than { loading: boolean; data?: T; error?: string }?

Check Your Understanding

What is the purpose of assigning const _check: never = state inside the default branch of a switch over a union?