Course contentsShow
← TypeScript
Lesson 915 of 1,79621. The unknown TypeFree lesson

instanceof for Class Narrowing

Using instanceof to narrow unknown to specific class instances like Error or Date.

instanceof for Class Narrowing

What you'll learn: How to use the instanceof operator to safely narrow unknown values to specific class instances like Error or Date.

The Core Idea

When you have a value typed as unknown, TypeScript won't let you access any properties or methods on it—that's the safety guarantee. But what if you need to check whether that unknown value is actually an Error or a Date or some custom class? That's where instanceof comes in.

The instanceof operator tests whether an object was created by a specific constructor function (class). When you use it in a type guard, TypeScript understands the check and narrows the unknown type to the specific class type.

How instanceof Narrows unknown

function handleUnknownValue(value: unknown) {
  if (value instanceof Error) {
    // TypeScript now knows value is Error
    console.log(value.message);
    console.log(value.stack);
  }
}

Before the instanceof check, value is unknown. After the check passes, TypeScript narrows it to Error, so you can safely access message and stack.

Common Built-in Classes

You'll often use instanceof with JavaScript's built-in classes:

function processUnknown(data: unknown) {
  if (data instanceof Date) {
    console.log(data.getFullYear());
  }

  if (data instanceof RegExp) {
    console.log(data.test("some string"));
  }

  if (data instanceof Array) {
    console.log(data.length);
  }
}

Combining with Other Guards

You can combine instanceof with other type guards you've learned:

function safeErrorMessage(value: unknown): string {
  if (typeof value === "string") {
    return value;
  }
  
  if (value instanceof Error) {
    return value.message;
  }
  
  return "Unknown error";
}

Key Takeaway: Use instanceof to narrow unknown values to specific class types, enabling safe access to class-specific properties and methods after the check succeeds.