classDatabaseErrorextendsError{}consterror=newDatabaseError("Unique constraint violation");// prints "true"console.log(errorinstanceofError);// incorrectly prints "false"console.log(errorinstanceofDatabaseError);
classDatabaseErrorextendsError{constructor(message:string){super(message);Object.setPrototypeOf(this,DatabaseError.prototype);classDatabaseConnectionErrorextendsDatabaseError{constructor(message:string){super(message);Object.setPrototypeOf(this,DatabaseConnectionError.prototype);consterror=newDatabaseConnectionError("Invalid credentials");// all print "true"console.log(errorinstanceofError);console.log(errorinstanceofDatabaseError);console.log(errorinstanceofDatabaseConnectionError);Enter fullscreen modeExit fullscreen mode
Remember that this is only an issue if your compilation target is ES3 or ES5. Instead of having to remember to set the prototype, you could consider upgrading your target to ES 2015 or even later. ES 2015 has over 97% browser support, so it may be a reasonable choice for you, especially if you are okay with dropping support for Internet Explorer.
Built on Forem — the open source software that powers DEV and other inclusive communities.