To extend the Error class with TypeScript, we can use the extend
keyword.
For instance, we write
class FooError extends Error {
constructor(m: string) {
super(m);
}
sayHello() {
return this.message;
}
}
to create the FooError
class that inherits from the Error
class by adding extends Error
.
In the constructor
, we call super
parent constructor with the arguments required by Error
.
And then we add the sayHello
method that’s exclusive to the FooError
class.
Conclusion
To extend the Error class with TypeScript, we can use the extend
keyword.