Course contentsShow
← TypeScript
Lesson 408 of 1,7969. Union TypesFree lesson

Narrowing with if/else Chains

Using if-else equality checks on the discriminant to access variant-specific properties.

Narrowing with if/else Chains

You'll learn how to use if-else equality checks on the discriminant property to safely access variant-specific properties in discriminated unions.

The Core Idea

You've learned that discriminated unions have a special property (the discriminant) that identifies which variant you're working with. The most straightforward way to narrow down which variant you have is using if/else chains that check the discriminant's value with equality operators like ===.

Once TypeScript sees you've checked discriminant === 'variantA', it knows inside that if block you're definitely dealing with variant A, so it lets you safely access A's unique properties.

How It Works

type Circle = { kind: 'circle'; radius: number };
type Square = { kind: 'square'; sideLength: number };
type Shape = Circle | Square;

function getArea(shape: Shape): number {
  if (shape.kind === 'circle') {
    // TypeScript knows shape is Circle here
    return Math.PI * shape.radius ** 2;
  } else {
    // TypeScript knows shape is Square here
    return shape.sideLength * shape.sideLength;
  }
}

The equality check shape.kind === 'circle' tells TypeScript exactly which variant you have. Inside the if block, shape.radius is safe. Inside the else block, only Square remains possible, so shape.sideLength is safe.

Think of It Like Sorting Mail

Imagine sorting packages by delivery type: "express" or "standard". You check the label (discriminant), then handle express packages in one pile and standard in another. Each pile gets the appropriate handling because you know what type you're dealing with.

Key Takeaway: Using if/else chains with equality checks on the discriminant property is the most readable way to narrow discriminated unions and safely access each variant's unique properties.