Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Type Guards & Discriminated Unio | TypeScript Mastery lesson | BraveProgrammer
  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 14 of 56

·Typescript

Type Guards & Discriminated Unions

20 minutes

Course progress25%

Type Guards

A type guard narrows a union type to a specific member.

function isString(x: unknown): x is string {
  return typeof x === "string";
}

 () {
   ((val)) {
    
    .(val.());
  }  {
    
    .(val.());
  }
}
function
foo
val: string | number
if
isString
// val is string here
console
log
toUpperCase
else
// val is number here
console
log
toFixed
2

in Operator Guard

type Cat = { kind: "cat"; meow(): void };
type Dog = { kind: "dog"; bark(): void };
type Pet = Cat | Dog;

function speak(pet: Pet) {
  if ("meow" in pet) {
    pet.meow();
  } else {
    pet.bark();
  }
}

Discriminated Unions (tagged unions)

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(s: Shape): number {
  switch (s.kind) {
    case "circle": return Math.PI * s.radius ** 2;
    case "square": return s.side ** 2;
  }
}

Info

The kind property acts as a discriminant, allowing exhaustive switch statements.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from TypeScript MasteryBrowse activities
Previous lessonUtility Types – `Partial`, `Pick`, `Omit`, `Readonly`Continue to lesson 15Tuples & ReadonlyArrayBack to TypeScript Mastery curriculum