Categories
TypeScript Answers

How to extending error class with TypeScript?

Spread the love

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.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.