TypeScript Union & Intersection Types, Type Guards, Discriminated Unions

Master TypeScript union types, intersection types, type guards, and discriminated unions!

Introduction

Union and intersection types are super powerful! Let's master them!

What You Will Learn

  • Union types (|)
  • Intersection types (&)
  • Type guards
  • Discriminated unions

Prerequisites

Union Types!

A type that can be one of several types!

type Status = "pending" | "approved" | "rejected";
let status: Status = "pending";
status = "approved";
// status = "something"; // Error!

type ID = string | number;
let id: ID = "abc123";
id = 42;

Type Guards!

Narrow down union types!

typeof Guard!

function printId(id: string | number) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(2));
  }
}

in Guard!

type Dog = { bark: () => void };
type Cat = { meow: () => void };
function makeSound(animal: Dog | Cat) {
  if ("bark" in animal) {
    animal.bark();
  } else {
    animal.meow();
  }
}

Discriminated Unions!

Pattern for type-safe unions!

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

function getArea(shape: Shape) {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius ** 2;
  } else {
    return shape.side ** 2;
  }
}

Intersection Types!

Combine multiple types!

type User = { name: string };
type Employee = { id: number };
type Staff = User & Employee;
const staff: Staff = { name: "John", id: 1 };

Best Practices

  1. Use discriminated unions: Great pattern!
  2. Write type guards: Narrow unions safely!
  3. Keep unions simple: Avoid too many options!

Summary

Union and intersection types are essential!

Related Articles

Previous Tutorial

Type Aliases

Next Tutorial

Let's learn generics! → Generics