To extending error class with TypeScript, we call Object.setPrototypeOf
to set the prototype of our error class.
For instance, we write
class FooError extends Error {
constructor(m: string) {
super(m);
Object.setPrototypeOf(this, FooError.prototype);
}
sayHello() {
return "hello " + this.message;
}
}
to create a FooError
class that extends the Error
class.
Then we call Object.setPrototypeOf
to set the prototype of this
to FooError.prototype
in the constructor.
this
then inherits from FooError.prototype
.
Then we can use Error
class methods without errors.
Conclusion
To extending error class with TypeScript, we call Object.setPrototypeOf
to set the prototype of our error class.