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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 14 of 56 · Typescript

Type Guards & Discriminated Unions

Duration: 20 minutes

Type Guards

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

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

function foo(val: string | number) {
  if (isString(val)) {
    // val is string here
    console.log(val.toUpperCase());
  } else {
    // val is number here
    console.log(val.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.

Previous: Utility Types – `Partial`, `Pick`, `Omit`, `Readonly`Next: Tuples & ReadonlyArray