Thuta Learning
AdvancedProgrammingintermediate

Type Narrowing and Type Guards

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Use built-in type guards
  • Build discriminated unions
  • Write exhaustive checks

Let's break this down simply

Type narrowing is how TypeScript pins a broad type down to a more specific one based on a runtime check. In a discriminated union, giving every branch a shared literal field means each branch can only access the properties that are actually valid for it.

typescript
type Result =
  | { status: 'success'; data: string[] }
  | { status: 'error'; message: string }

function render(result: Result): string {
  switch (result.status) {
    case 'success':
      return `Found ${result.data.length} items`
    case 'error':
      return `Error: ${result.message}`
  }
}

console.log(render({ status: 'success', data: ['Vue', 'TypeScript'] }))
You should see
Found 2 items

Try it yourself

Build a discriminated union of Circle and Rectangle, and write a function that calculates the area for each shape.

TypeScript Handbook — NarrowingTypeScript

Easy traps

  • Force-bypassing the compiler with a type assertion
  • Typing the discriminant field as a generic string

Exercise

Build a discriminated union of Circle and Rectangle, and write a function that calculates the area for each shape.

You'll know it worked when: Found 2 items

Type Narrowing and Type Guards | Thuta Learning