繁体   English   中英

如何在接口中未定义的 typescript class 中插入属性

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

我有一个使用 typescript 的快速应用程序。 我正在尝试使用自定义错误处理程序,因为我正在尝试扩展错误 class。

错误响应.ts

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

typescript 给出错误,因为我扩展的错误接口具有以下定义

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

目前对于解决方法,我已将其设为 javascript 文件。 但是如何将其用作 typescript 文件并正确使用它。 以便属性 statusCode 和 errorCode 不会给出 ts 错误。

使用的版本 "typescript": "^4.0.3"

您似乎想扩展Error class 并增加两个新字段,正确的做法是:

TS Playground 链接

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是一个接口ErrorResponse是一个class 所以ErrorResponse不能扩展Error但可以实现它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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