Course contentsShow
← TypeScript
Lesson 198 of 1,7965. Type Narrowing FundamentalsFree lesson

typeof Guards in Practice

Real-world patterns for using typeof guards in function parameters and generic code.

typeof Guards in Practice

You'll learn: How to apply typeof guards in real-world functions and flexible code patterns.

From Theory to Practice

You've learned individual typeof checks. Now let's see how they solve real problems. In practice, typeof guards shine in function parameters where you accept multiple types and need to handle each differently, and in generic utility code that must adapt to whatever values it receives.

Common Real-World Patterns

Multi-Type Function Parameters

function formatValue(value: string | number): string {
  if (typeof value === 'string') {
    // value is string here
    return value.toUpperCase();
  }
  // value is number here
  return value.toFixed(2);
}

Think of this like a receptionist who checks ID types: "Driver's license? Go to counter A. Passport? Counter B."

Defensive Coding

function processInput(input: unknown): string {
  if (typeof input === 'string') {
    return input.trim();
  }
  if (typeof input === 'number') {
    return input.toString();
  }
  return 'Invalid input';
}

When you don't control what data arrives, typeof guards let you handle whatever comes gracefully.

Configuration Options

function setVolume(level: number | boolean): void {
  if (typeof level === 'boolean') {
    // true = max volume, false = mute
    console.log(level ? 100 : 0);
  } else {
    console.log(level);
  }
}

APIs often accept "convenient shortcuts" alongside precise values. typeof guards make this type-safe.

Why This Matters

Without typeof guards, you'd need separate functions or resort to any, losing type safety. With them, you write flexible APIs that remain fully type-checked.

Key Takeaway: Real-world TypeScript code uses typeof guards to write functions that safely accept multiple input types, handle unknown data defensively, and provide flexible APIs without sacrificing type safety.