22

Why does this result in false?

'use strict';

class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    this.name = 'InvalidCredentialsError';
  }
}

const err = new InvalidCredentialsError('');

console.log(err instanceof InvalidCredentialsError);

But this returns true:

console.log(err instanceof Error);

enter image description here

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • What is `err`? Do you mean `const errClass = new InvalidCredentialsError(); console.log(errClass instanceof Error);`? – evolutionxbox Jan 18 '17 at 12:16
  • 1
    It also looks like `err` is `undefined` in the code you've provided, and `errClass` is not a class instance, but a reference to the class itself. – evolutionxbox Jan 18 '17 at 12:19
  • @evolutionxbox Apologize! I forgot to copy the complete code! Updated now :) – basickarl Jan 18 '17 at 12:25
  • Your updated code now produces a true evaluation... not false. – evolutionxbox Jan 18 '17 at 12:26
  • @evolutionxbox http://codepen.io/anon/pen/RKKwJJ?editors=0011 – basickarl Jan 18 '17 at 12:27
  • @evolutionxbox The first instanceof is false, this is what I'm confused about! – basickarl Jan 18 '17 at 12:27
  • 1
    That's odd. When I run this code in Chrome I get `true` and `true`. – evolutionxbox Jan 18 '17 at 12:28
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/133447/discussion-between-evolutionxbox-and-karl-morrison). – evolutionxbox Jan 18 '17 at 12:29
  • 2
    It's a transpiler limitation. See also [this](http://stackoverflow.com/q/30402287/1048572). – Bergi Jan 18 '17 at 12:38
  • @Bergi Alright! – basickarl Jan 18 '17 at 12:55
  • This is also a known limitation in TypeScript. See [this blog post](https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/) and [GitHub issue](https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work). As workaround, set the prototype manually at the end of the constructor: `Object.setPrototypeOf(this, InvalidCredentialsError.prototype);` – mihca Aug 09 '21 at 08:35

1 Answers1

7

This works...you need to construct an instance of your type, then instanceof will return whether your object is indeed an instance of that type.

'use strict';

class InvalidCredentialsError extends Error {
  constructor(msg) {
    super(msg);
    this.name = 'InvalidCredentialsError';
  }
}

var err = new InvalidCredentialsError("Hello, world!");

console.log(err instanceof InvalidCredentialsError); // true

Note const errClass = InvalidCredentialsError; will just create an alias for your type, so you could do this...

var err = new errClass("Hello, alias");
console.log(err instanceof errClass); // true
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313