Custom Errors in TypeScript 2.1
TypeScript 2.1 introduced a number of breaking changes, among them that “Extending built-ins like Error, Array, and Map may no longer work”.
For a subclass like the following:
- methods may be undefined on objects returned by constructing these subclasses, so calling sayHello will result in an error.
instanceofwill be broken between instances of the subclass and their instances, so (
new FooError()) instanceof FooErrorwill return
The suggested solution of manually adjusting the prototype with
Object.setPrototypeOf(this, FooError.prototype) might not work due to
Object.setPrototypeOf(..) being missing.
After trying several approaches, the solution presented here seems to be the way which reliably works, including with promises (native and bluebird):
If you have suggestions or feedback, let me know via @metachris.