Home > Net >  overriding the entire class possible in typescript
overriding the entire class possible in typescript

Time:04-01

I have a class defined like this:

baseException.ts

/**
 * Override the default Error.
 *
 * @class Error
 * @extends {Error}
 */
class Error {
  /**
   * @type {string}
   * @memberof Error
   */
  message: string;

  /**
   * @type {boolean}
   * @memberof Error
   */
  isCustom: boolean;

  /**
   * @type {number}
   * @memberof Error
   */
  statusCode: number;

  /**
   * @param {string} message
   * @param {number} statusCode
   * @memberof Error
   */
  constructor(message: string, statusCode: number) {
    this.isCustom = true;
    this.message = message;
    this.statusCode = statusCode;
  }
}    

All the rest of the code derive from this base class such as:
import Error from baseException
ForbiddenError extends Error
and we use this without error:

throw new ForbiddenError

But, why doesn't the base class Error do something like:

class Error extends Error , there's no extend keyword, so how's it getting the behaviour of the base class?

CodePudding user response:

The throw statement throws a user-defined exception.

When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

throw 'Error2'; // generates an exception with a string value
throw 42;       // generates an exception with the value 42
throw true;     // generates an exception with the value true
throw new Error('Required');  // generates an error object with the message of Required

So you can throw everything, and you do not need to have to extends the Error class.

The comments are document comments, yeah, but are still comments, so they do not interfere with the compiler.

  • Related