Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. TypeScript Dictionary
  3. instanceof Guard

instanceof Guard

Since: TypeScript 1.0(2014)

The instanceof guard is a type guard that checks whether an object is an instance of a specific class, narrowing the type accordingly. It is commonly used in code with class hierarchies.

Syntax

x instanceof ClassName

Sample Code

class TextProcessor {
  process() { return 'Text processing complete'; }
}

class ImageProcessor {
  convert() { return 'Image conversion complete'; }
}

function handle(processor: TextProcessor | ImageProcessor): string {
  if (processor instanceof TextProcessor) {
    // Here, processor is narrowed to: TextProcessor
    return processor.process();
  } else {
    // Here, processor is narrowed to: ImageProcessor
    return processor.convert();
  }
}

// Narrowing within a class hierarchy
class BaseHandler {
  name: string;
  constructor(name: string) { this.name = name; }
}

class PriorityHandler extends BaseHandler {
  priority() { return `${this.name} is a priority handler`; }
}

function dispatch(handler: BaseHandler): void {
  if (handler instanceof PriorityHandler) {
    // Here, handler is narrowed to: PriorityHandler
    console.log(handler.priority());
  } else {
    // Here, handler is narrowed to: BaseHandler (not PriorityHandler)
    console.log(`${handler.name} has been registered`);
  }
}

// Distinguishing Error classes
function handleError(err: unknown): string {
  if (err instanceof TypeError) {
    return `Type error: ${err.message}`;
  }
  if (err instanceof RangeError) {
    return `Range error: ${err.message}`;
  }
  return 'Unknown error';
}

Overview

instanceof is a native JavaScript operator that checks whether an object is an instance of a class by traversing the constructor's prototype chain. TypeScript recognizes it as a type guard and automatically narrows the type within the conditional block.

Interfaces and type aliases do not exist at runtime, so they cannot be checked with instanceof. To narrow types based on interfaces, use the in operator guard or a user-defined type guard.

Exceptions caught in a catch block are treated as the unknown type. To identify the kind of error and handle it appropriately, checks like instanceof Error or instanceof TypeError are effective.

If you find any errors or copyright issues, please .