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

The in Operator for Property Checking

How the 'in' operator checks for property existence and narrows union types based on discriminating properties.

The in Operator for Property Checking

You'll learn how to narrow union types by checking whether a specific property exists on an object.

What the in Operator Does

The in operator is a JavaScript feature that checks if a property exists on an object. In TypeScript, it becomes a powerful type guard that helps narrow union types based on which properties are present.

Think of it like a security checkpoint: "Does this object have a VIP badge?" If yes, TypeScript knows it's a VIP member with specific permissions (properties). If no, it must be a different type of member.

How It Works

When you have a union type where each member has unique properties (called discriminating properties), the in operator lets TypeScript figure out which specific type you're working with:

type Dog = { bark: () => void; breed: string };
type Cat = { meow: () => void; color: string };

function interact(animal: Dog | Cat) {
  if ('bark' in animal) {
    // TypeScript knows: animal is Dog
    animal.bark();
    console.log(animal.breed);
  } else {
    // TypeScript knows: animal is Cat
    animal.meow();
    console.log(animal.color);
  }
}

The 'bark' in animal check narrows the type from Dog | Cat to just Dog inside that block. The property name must be a string literal, and TypeScript tracks which type has that property.

Why This Matters

Without the in operator, you'd lose type safety when working with union types that differ by shape rather than by a single discriminant field.

Key Takeaway: The in operator checks property existence and narrows union types, letting TypeScript understand which specific type you're working with based on its unique properties.