简体   繁体   中英

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"

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

Class Error is an interface , and ErrorResponse is a class . So ErrorResponse can't extend Error but can implement it.

export default class ErrorResponse implements Error { // class 'implements' interface
    constructor(message, statusCode, errorCode) {
        this.message = message;
        this.statusCode = statusCode;
        this.errorCode = errorCode;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM