Course contentsShow
← TypeScript
Lesson 133 of 1,7963. Basic TypesFree lesson

Narrowing unknown with instanceof and in

Apply structural checks to narrow unknown to object or class types.

Narrowing unknown with instanceof and in

What you'll learn: How to safely check if an unknown value is an object or class instance before using its properties.


The Core Idea

When you have an unknown value, typeof can tell you if it's a primitive, but what if it's an object? You need ways to check:

  1. Is it an instance of a specific class? → Use instanceof
  2. Does it have a specific property? → Use the in operator

These structural checks let TypeScript narrow unknown to something more useful.


Using instanceof

Think of instanceof as asking: "Was this value created by this class?" If true, TypeScript knows the value has that class's shape:

function processValue(value: unknown) {
  if (value instanceof Date) {
    // TypeScript now knows value is a Date
    console.log(value.getFullYear());
  }
}

After the instanceof check, value is treated as a Date, so you can call getFullYear() safely.


Using the in Operator

The in operator checks if a property exists on an object:

function logName(value: unknown) {
  if (typeof value === "object" && value !== null && "name" in value) {
    // TypeScript knows value is an object with a 'name' property
    console.log(value.name);
  }
}

Notice the guards: first confirm it's an object and not null, then check for the property. This pattern is common when dealing with plain objects.


Key Takeaway: Use instanceof to narrow unknown to class instances and in to check for properties on objects—both let you safely access structure without losing type safety.