Sometimes, we want to extend the Error class with TypeScript.
In this article, we’ll look at how to extend the Error class with TypeScript.
How to extend the Error class with TypeScript?
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.