[英]how to insert a property in typescript class which is not defined in the interface
i have a express app using typescript.我有一个使用 typescript 的快速应用程序。 there i am trying to use custom error handler for that i am trying to extend the error class.
我正在尝试使用自定义错误处理程序,因为我正在尝试扩展错误 class。
errorResponse.ts错误响应.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 typescript 给出错误,因为我扩展的错误接口具有以下定义
interface Error {
name: string;
message: string;
stack?: string;
}
currently for workaround i have made it a javascript file.目前对于解决方法,我已将其设为 javascript 文件。 but how to use this as typescript file and use it correctly.
但是如何将其用作 typescript 文件并正确使用它。 so that the properties statusCode & errorCode does not give ts error.
以便属性 statusCode 和 errorCode 不会给出 ts 错误。
version used "typescript": "^4.0.3"使用的版本 "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:您似乎想扩展
Error
class 并增加两个新字段,正确的做法是:
TS Playground link 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
is an interface , and ErrorResponse
is a class . Class
Error
是一个接口, ErrorResponse
是一个class 。 So ErrorResponse
can't extend Error
but can implement it.所以
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.