4

我有以下界面:

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 没有实现接口。我不明白它是如何检查它的,虽然它在构建阶段根据接口填充了所有内容,如果用 JavaScript 编写,这将工作正常,在 Closure 工具中类型检查同样的东西也能完美工作。这个想法是我想将接口实现为一个类,这样我就可以在原型中拥有实用方法,但仍然能够轻松地转换为 JSON 字符串。

有任何想法吗?

谢谢

4

1 回答 1

7

语言服务将静态分析您的接口声明,并且因为您已经表示它需要您的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;
})();
于 2012-10-08T12:48:04.977 回答