我有一个抽象错误类用于继承服务错误,以使错误处理更容易一些。 (ErrorBase来自https://gist.github.com/justmoon/15511f92e5216fa2624b#gistcomment-1928632)
export abstract class ServiceError extends ErrorBase {
abstract statusCode(): number;
abstract readonly errorCode: string;
static readonly defaultMessage: string;
constructor(readonly context?: any, message?: string) { super(message); }
toJSON(key: any) {
return {
errorCode: this.errorCode,
message: this.message,
context: this.context
};
}
}
这是一个扩展它的类的示例:
export class ExampleError extends ServiceError {
statusCode(): number { return 400; }
errorCode: string = "err-example";
static readonly defaultMessage = "This is an example error";
constructor(context?: any, message?: string) {
super(context, message ? message : ExampleError.defaultMessage);
}
}
我一直在试图找出一种从基类构造函数内部访问继承类的defaultMessage 的方法,以便我可以简化继承类的构造函数。有什么办法可以做到这一点吗?
最佳答案
静态属性只是在原型(prototype)函数上定义的属性。他们像这样编译:
// TypeScript
class A {
public static property = 'my string';
}
// Compiled ES5 JavaScript
function A() {}
A.property = 'my string';
因此,您可以使用constructor
this
上的属性来访问用于构造实例(或更确切地说是复制)的派生类/函数:
class A {
public static defaultMessage = 'My Error A';
constructor() {
// will output "My Error B" if a instance of B is being constructed
console.log(this.constructor['defaultMessage']);
}
}
class B {
public static defaultMessage = 'My Error B';
}
关于node.js - Typescript:在调用 super 之前从基类构造函数访问继承类的静态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48199213/