Why instanceof returns false for a child object in Javascript Why instanceof returns false for a child object in Javascript typescript typescript

Why instanceof returns false for a child object in Javascript


This is a documented bug:

https://github.com/Microsoft/TypeScript/issues/15875

Extending built-ins like Error, Array, and Map may no longer work

As part of substituting the value of this with the value returned by a super(...) call, subclassing Error, Array, and others may no longer work as expected. This is due to the fact that constructor functions for Error, Array, and the like use ECMAScript 6's new.target to adjust the prototype chain; however, there is no way to ensure a value for new.target when invoking a constructor in ECMAScript 5. Other downlevel compilers generally have the same limitation by default.

The recommendation is to adjust the prototype manually using setPrototypeOf in the constructor. A fix for your PullCreditError class would look like this:

export class PullCreditError extends Error {  public name: string;  public message: string;  public attemptsRemaining: number;  constructor(message: string, attemptsRemaining: number) {    super();    Object.setPrototypeOf(this, PullCreditError.prototype); // <-------    Error.captureStackTrace(this, PullCreditError);    this.name = 'PullCreditError';    this.message = message;    this.attemptsRemaining = attemptsRemaining;  }}