Categories
TypeScript Answers

How to extend the Error class with TypeScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.