📘

Type Guards and Type Narrowing

Intermediate
100 XP
40 min
Lesson Content

Type Guards

Type guards help TypeScript narrow down types, making your code safer and more predictable.

typeof Guards

function process(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase(); // TypeScript knows it's string
  }
  return value.toString(); // TypeScript knows it's number
}

instanceof Guards

class Dog { bark() {} }
class Cat { meow() {} }

function makeSound(animal: Dog | Cat) {
  if (animal instanceof Dog) {
    animal.bark(); // TypeScript knows it's Dog
  } else {
    animal.meow(); // TypeScript knows it's Cat
  }
}

Custom Type Guards

interface Fish { swim(): void; }
interface Bird { fly(): void; }

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}
Example Code

Use type guards to narrow types

function formatValue(value: string | number | boolean): string {
  if (typeof value === "string") {
    return `Text: ${value}`;
  } else if (typeof value === "number") {
    return `Number: ${value}`;
  } else {
    return `Boolean: ${value}`;
  }
}

console.log(formatValue("hello"));
console.log(formatValue(42));

Expected Output:

Text: hello
Number: 42
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code