如何在TypeScript中扩展宿主对象(例如,错误) [英] How do I extend a host object (e.g. Error) in TypeScript
本文介绍了如何在TypeScript中扩展宿主对象(例如,错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将主机对象错误
扩展为自定义 UploadError
类。以下示例在编译时失败:
I would like to extend the host object Error
to a custom UploadError
class. The following example fails when I compile:
class UploadError extends Error {
constructor(message: string, private code: number) {
super(message);
}
getCode(): number {
return this.code;
}
}
当我运行TypeScript编译器时 tsc
我收到以下错误:
When I run the TypeScript compiler tsc
I get the following error:
UploadError.ts(1,0): A export class may only extend other classes, Error is an interface.
似乎错误
被定义为接口。如果有人知道实现的名称是什么,它会让我非常高兴: - )
It seems Error
is defined as an interface. If anyone knows what the name of the implementation is it would make me very happy :-)
function UploadError (message: string, code: number) {
this.message = message;
this.code = code;
}
UploadError.prototype = new Error();
UploadError.prototype.constructor = UploadError;
UploadError.prototype.getCode = (): number => {
return this.code;
}
推荐答案
我找到了以下方法有效:
I have found the following approach works:
declare class ErrorClass implements Error {
public name: string;
public message: string;
constructor(message?: string);
}
var ErrorClass = Error;
class MyError extends ErrorClass {
public name = "MyError";
constructor (public message?: string) {
super(message);
}
}
生成的脚本如下所示:
var ErrorClass = Error;
var MyError = (function (_super) {
__extends(MyError, _super);
function MyError(message) {
_super.call(this, message);
this.message = message;
this.name = "MyError";
}
return MyError;
})(ErrorClass);
这篇关于如何在TypeScript中扩展宿主对象(例如,错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文