Search code examples
javascripttypescripterror-handlingextends

how to insert a property in typescript class which is not defined in the interface


i have a express app using typescript. there i am trying to use custom error handler for that i am trying to extend the error class.

errorResponse.ts

export default class ErrorResponse extends Error {
    constructor(message, statusCode, errorCode) {
        super(message);
        this.statusCode = statusCode;
        this.errorCode = errorCode;
    }
}

typescript is giving error as the error interface which i extend has the following definition

interface Error {
    name: string;
    message: string;
    stack?: string;
}

currently for workaround i have made it a javascript file. but how to use this as typescript file and use it correctly. so that the properties statusCode & errorCode does not give ts error.

version used "typescript": "^4.0.3"


Solution

  • It seems like you want to extend Error class and augment it with two new fields, the right way to do that is this:

    TS Playground link

    export default class ErrorResponse extends Error {
      constructor(
        message: string,
        public statusCode: number,
        public errorCode: string
      ) {
        super(message);
      }
    }
    
    const e = new ErrorResponse("something", 404, "Not found");
    e.errorCode; // works
    e.message; // works
    e.name; // works