TypeScript Essentials: Structural Typing & Type Narrowing
JavaScript is dynamically typed: variables can hold any value, and type errors are only discovered when users crash into them at runtime.
TypeScript solves this by adding a compile-time static type layer over JavaScript. It catches bugs while you are writing code in your editor, then strips away all types during compilation (type erasure), leaving pure, optimized JavaScript.
Two foundational concepts set TypeScript apart from traditional languages like Java or C++:
- Structural Typing (Duck Typing)
- Type Narrowing (Control Flow Analysis)
1. Structural Typing vs. Nominal Typing
In nominal languages (like Java or C#), an object is only compatible with a type if it explicitly declares that it implements it:
// Java (Nominal Typing):class Person {}class Employee {}// ❌ Error in Java even if both classes have identical fields:Person p = new Employee();In TypeScript, types are Structural ("If it walks like a duck and quacks like a duck, it is a duck"). Two types are interchangeable as long as their internal shapes match:
type Point2D = { x: number; y: number };type Vector2D = { x: number; y: number };const pt: Point2D = { x: 10, y: 20 };const vec: Vector2D = pt; // ✅ 100% valid in TypeScript! Shapes are identical.2. Union Types & The Narrowing Problem
A union type models a value that can be one of several possibilities:
function printId(id: string | number) { // ❌ Error: Property 'toUpperCase' does not exist on type 'string | number'. // Property 'toUpperCase' does not exist on type 'number'. console.log(id.toUpperCase());}Because id could be a number, TypeScript forbids calling .toUpperCase() on the union. To use it safely, you must narrow the type.
3. Interactive Type Narrowing & Discriminated Unions Studio
Explore how TypeScript's compiler follows code paths to narrow unions, inspect discriminated unions, and verify exhaustiveness checking using never.
TypeScript Type Narrowing & Discriminated Unions Studio
Type Safety EngineWatch TypeScript's control flow analysis narrow broad union types into specific safe shapes in real time.
The Tagged / Discriminated Union Pattern
Every variant in the union shares a single common literal property (the “discriminant”, here status). Checking this tag allows TypeScript to automatically narrow down to the exact shape and properties!
type AsyncResult =
| { status: "loading" }
| { status: "success"; data: string[] }
| { status: "error"; message: string };
function render(res: AsyncResult) {
switch (res.status) {} }
res.data in the "loading" case will trigger TypeScript error Property 'data' does not exist on type { status: "loading" }.4. The 4 Ways to Narrow Types in TypeScript
1. typeof Type Guards
For primitive types (string, number, boolean, symbol, bigint):
function formatPrice(value: string | number): string { if (typeof value === "string") { // TypeScript narrows value to string: return "$" + value.trim(); } // TypeScript deduces value MUST be number: return "$" + value.toFixed(2);}2. The in Operator Guard
For narrowing by testing if a property exists on an object:
type Fish = { swim: () => void };type Bird = { fly: () => void };function move(animal: Fish | Bird) { if ("swim" in animal) { animal.swim(); // animal narrowed to Fish } else { animal.fly(); // animal narrowed to Bird }}3. instanceof Guard
For classes and constructor instances:
function logTimestamp(date: Date | string) { if (date instanceof Date) { console.log(date.toISOString()); // date narrowed to Date } else { console.log(date); // date narrowed to string }}4. Discriminated Unions (The Tagged Union Pattern)
The single most powerful architectural pattern in TypeScript. Every shape shares a common literal property (the discriminant tag):
type NetworkState = | { status: "idle" } | { status: "loading" } | { status: "success"; data: string[] } | { status: "error"; error: Error };function handleResponse(state: NetworkState) { switch (state.status) { case "idle": return "Ready to fetch"; case "loading": return "Fetching data..."; case "success": return `Loaded ${state.data.length} items`; case "error": return `Failed: ${state.error.message}`; }}5. Exhaustiveness Checking with the never Type
What happens if a teammate adds a new variant to NetworkState (e.g. { status: "cancelled" }), but forgets to update the switch statement?
You can use the never type to force the TypeScript compiler to throw an error if any variant is left unhandled:
function assertNever(x: never): never { throw new Error("Unexpected object: " + x);}function handleResponse(state: NetworkState) { switch (state.status) { case "idle": return "Idle"; case "loading": return "Loading"; case "success": return "Success"; case "error": return "Error"; default: // If any state was omitted, state is NOT 'never', causing compile error! return assertNever(state); }}6. Flashcards & Core Concepts
What is Structural Typing in TypeScript?
What is a Discriminated Union?