

How to Fix instanceof Not Working For Custom Errors in TypeScript
source link: https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Fix instanceof Not Working For Custom Errors in TypeScript
In JavaScript, you can create custom errors by extending the built-in Error object (ever since ES 2015).
class DatabaseError extends Error {}
You can do the same thing in TypeScript, but
there is an important caveat if your tsconfig.json
has a compilation
target of ES3 or ES5. In that
case, instanceof
doesn’t work, which breaks any logic that is based on whether
or not an error is a case of the custom error.
class DatabaseError extends Error {}
const error = new DatabaseError("Unique constraint violation");
// prints "true"
console.log(error instanceof Error);
// incorrectly prints "false"
console.log(error instanceof DatabaseError);
You can try this out yourself in the TypeScript playground. This is a known issue that started with TypeScript version 2.1. The recommended fix is to manually set the prototype in the constructor.
class DatabaseError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, DatabaseError.prototype);
}
}
const error = new DatabaseError("Unique constraint violation");
// both print "true" now
console.log(error instanceof Error);
console.log(error instanceof DatabaseError);
Any custom errors which further extend DatabaseError
still need the same
adjustment.
class DatabaseError extends Error {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, DatabaseError.prototype);
}
}
class DatabaseConnectionError extends DatabaseError {
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, DatabaseConnectionError.prototype);
}
}
const error = new DatabaseConnectionError("Invalid credentials");
// all print "true"
console.log(error instanceof Error);
console.log(error instanceof DatabaseError);
console.log(error instanceof DatabaseConnectionError);
Upgrade the Compilation Target
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.
Recommend
-
73
typeof 实现原理 typeof 一般被用于判断一个变量的类型,我们可以利用 typeof 来判断number, string, object, boolean, function, undefined, symbol 这七种类型,这种判断能帮助
-
51
最近在做 Code Review 的时候,发现了一些小问题,查出结果之后发现竟然是因为 typeof 和 instanceof 引发的。 这属于 JS 的基础知识,正是由于太基础了,所以很容易被忽略,导致项目中随处可见的滥用。
-
38
AuthorBrian GoetzOwnerGavin BiermanTypeFeatureScopeSEStatusClosed / DeliveredRelease...
-
25
AuthorBrian Goetz OwnerJan LahodaTypeFeatureScopeSEStatusClosed / DeliveredRelease15...
-
30
Java: Pattern Matching for instanceof This article describes a preview feature, JEP draft: Patter...
-
18
Pattern Matching for instanceof (Second Preview) JEP proposed to target JDK 15: 375: Pattern Matching for instanceof (Second Preview) mark.reinhold at oracle.com
-
49
pattern matching for instanceof – Inside.java Inside Java News and views from the Java tea...
-
18
-
9
Type checking in JavaScript: typeof and instanceof operatorsJavaScript is a loosely-typed language, so there is no restriction on the variable’s type. For example, if you’ve created a variable with a string type, later you c...
-
10
JS数据类型检测typeof、instanceof、constructor、Object.prototype.toString.call(val)的区别
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK