Course contentsShow
← TypeScript
Lesson 919 of 1,79621. The unknown TypeFree lesson

Combining Multiple Guards

Chaining typeof, in, and other checks to progressively narrow unknown to precise types.

Combining Multiple Guards

What you'll learn: How to chain typeof, in, instanceof, and other type guards together to progressively narrow unknown values down to the precise types you need.

The Progressive Narrowing Strategy

When you have an unknown value, you rarely need just one check. Real-world data—especially from JSON parsing, API responses, or user input—requires multiple validations before TypeScript can trust the type.

Think of type guards like security checkpoints at an airport. One checkpoint verifies your ticket, another checks your ID, and a third scans your luggage. Each checkpoint narrows down who you are until you're fully verified. Similarly, you combine type guards to narrow unknown through multiple steps.

Chaining Guards with Logical Operators

You can combine guards using && (and) or nest them with if statements:

function processValue(value: unknown): string {
  // Step 1: Ensure it's an object
  if (typeof value === "object" && value !== null) {
    // Step 2: Check for a specific property
    if ("name" in value && "age" in value) {
      // Step 3: Validate property types
      if (typeof value.name === "string" && typeof value.age === "number") {
        // Now TypeScript knows: { name: string; age: number; ... }
        return `${value.name} is ${value.age} years old`;
      }
    }
  }
  return "Invalid data";
}

Each guard narrows the type further, unlocking access to more properties and operations.

Mixing Different Guard Types

You can freely combine typeof, in, instanceof, and custom predicates:

function handleInput(input: unknown): void {
  if (typeof input === "object" && input !== null) {
    if (input instanceof Date) {
      console.log(input.toISOString());
    } else if ("message" in input && typeof input.message === "string") {
      console.log(input.message.toUpperCase());
    }
  }
}

Here, typeof confirms it's an object, then instanceof and in narrow to specific shapes.

Key Takeaway: Combining type guards lets you safely narrow unknown values through multiple validation steps, progressively building confidence in the type until TypeScript grants full access to properties and methods.