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.
- 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:
// 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):
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:
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?
| Feature | interface | type |
|---|---|---|
Object shapes & class contracts (implements) | Great | Great |
Union types ("idle" | "loading") & tuples | No | Required |
Mapped / Utility types (Partial, Omit) | Limited | Required |
| Extending | interface 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):tsinterface 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:
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
Why are Discriminated Unions ({ status: 'loading' } | { status: 'success'; data: T }) better than { loading: boolean; data?: T; error?: string }?
What is the purpose of assigning const _check: never = state inside the default branch of a switch over a union?