node.js - Typescript:在调用 super 之前从基类构造函数访问继承类的静态属性?

标签 node.js typescript

我有一个抽象错误类用于继承服务错误,以使错误处理更容易一些。 (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/

相关文章:

javascript - Socket.IO - 回调仅发出的用户

javascript - Angular2 - 防止复选框被选中

javascript - 基于 if 语句动态改变图像

css - Angular - 选择选项卡时重新加载页面?

node.js - 如何防止 mongoose 中的字段更新

node.js - 如何使用node.js lib更新Elasticsearch中的项目?

javascript - Angular 给出了一个奇怪的 templateURL

node.js - 使用 node-inspector 调试 Node/Express RESTful API

javascript - Vue 子 Prop 不会在父项中的绑定(bind)值更改时更新

css - Rxjs 鼠标事件以在 Angular 6 中实现所需的功能