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

in Operator with Optional Properties

How TypeScript narrows when checking optional properties with 'in' and the difference from undefined checks.

in Operator with Optional Properties

You'll learn how TypeScript narrows optional properties differently when using in versus checking for undefined.

When you use the in operator to check for an optional property, TypeScript narrows based on whether that property exists as a key on the object, regardless of its value. This is subtly different from checking if a property equals undefined.

The Core Difference

An optional property like age?: number can exist in three states:

  1. Present with a value: { age: 25 }
  2. Present but explicitly undefined: { age: undefined }
  3. Not present at all: {}

The in operator checks for states 1 and 2 — it returns true if the property key exists, even when the value is undefined. A direct undefined check would only distinguish state 2 from the others.

type Person = {
  name: string;
  age?: number;
};

function checkPerson(person: Person) {
  if ('age' in person) {
    // TypeScript narrows to: age is present (could be number | undefined)
    const ageValue = person.age; // number | undefined
  }
}

Inside the if ('age' in person) block, TypeScript knows the age property exists, but it hasn't eliminated undefined as a possible value. The type is narrowed from "optional" to "definitely present, but possibly undefined."

This matters when objects are created dynamically or properties are conditionally added. The in operator is your tool for checking property presence, not property truthiness.

Key Takeaway: The in operator narrows optional properties by confirming the key exists on the object, but doesn't eliminate undefined from the value type — you're checking for presence, not defined-ness.