If TypeScript is configured to compile to ES5 or an earlier version of JavaScript before ES2015, it cannot properly subclass Error
due to limitations pre-ES2015. Instead, it generates something that resembles an Error
but not a CustomError
in your scenario. When TypeScript targets ES2015 or newer versions, it functions correctly.
In the case of setting ES5 output for your CustomError
code, the resulting JavaScript appears as follows:
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var CustomError = /** @class */ (function (_super) {
__extends(CustomError, _super);
function CustomError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return CustomError;
}(Error));
var error = new CustomError();
console.log(error instanceof Error); // true
console.log(error instanceof CustomError); // true
Playground Link
However, when targeting ES2015 and above, proper inheritance from Error
(and Array
, which faced similar issues) becomes feasible. The following is your code set to target ES2015:
"use strict";
class CustomError extends Error {
}
const error = new CustomError();
console.log(error instanceof Error); // true
console.log(error instanceof CustomError); // true
This demonstrates true
, true
.
Playground Link
The great news is that as of 2022, unless you require support for outdated environments like IE11, you can update your TypeScript configuration to target at least ES2015, likely even a more advanced version.