TypeScript:可以在构造函数中实现接口(interface)吗?

标签 typescript

我有以下界面:

interface SMJSPacket {
  header: {
    tag: string;
    method: string;
    type: string;
  };
  response?: {
    status: string;
    content: string;
  };
  event?: {
    key?: string;
    action?: string;
  };
  request?: {
    run?: string;
  };
}

然后我想将它实现为一个类,并在构造函数中设置属性:

  class Request implements SMJSPacket {
    constructor(data: any, method: string) {
      this.header = {
        type: 'request',
        method: method || 'calld',
        tag: Request.getTag()
      }
      this.request = data;
    }
    static getTag(): string {
      return '_' + goog.now() + '_' + utils.getRandomBetween(1, 1000);
    }
  }

但是根据编译器 Request 没有实现接口(interface)。我不明白它是如何检查它的,虽然它在构造阶段根据界面填充了所有内容,如果用 JavaScript 编写,这会工作正常,在 Closure 工具中进行类型检查也可以完美工作。我的想法是我想将接口(interface)实现为一个类,这样我就可以在原型(prototype)中使用实用方法,但仍然能够轻松地转换为 JSON 字符串。

有什么想法吗?

谢谢

最佳答案

语言服务将静态分析您的接口(interface)声明,并且因为您已经表示它需要您的 header 成员,所以它应该构成类声明的一部分:

class Request implements SMJSPacket {
    header: { tag: string; method: string; type: string; };

    constructor(data: any, method: string) {
        this.header = {
            type: "request",
            method: (method || "calld"),
            tag: Request.getTag()
        };
    }

    static getTag(): string {
        return "tag stuff";
    }
}

别担心,输出的 javascript 更精简:

var Request = (function () {
    function Request(data, method) {
        this.header = {
            type: "request",
            method: (method || "calld"),
            tag: Request.getTag()
        };
    }
    Request.getTag = function getTag() {
        return "tag stuff";
    }
    return Request;
})();

关于TypeScript:可以在构造函数中实现接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12780391/

相关文章:

angular - 在 Material Angular 中显示一个简单的警告对话框

javascript - 有没有办法为 Typescript 中的嵌套键访问创建类型保护?

javascript - 为什么在窗口对象前加上前缀 "<any>"?

javascript - 如何从 Protractor 中的表中收集和返回聚合数据作为数组?

javascript - 哪个范围在对象内的 JavaScript 函数中表示 this?

typescript - Cypress 10 : Custom command is not a function

javascript - Angular Validator 检查输入是否为数字

javascript - canActivate 导致不断刷新 - Angular2+

javascript - 向多个父级发送事件以触发函数 Angular 5

angular - 避免在循环中使用嵌套可观察订阅的正确方法是什么?