TypeScript:在构造函数中实现接口可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12780391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:13:39  来源:igfitidea点击:

TypeScript: Implementing interface in the constructor possible?

typescript

提问by Peter StJ

I have the following interface:

我有以下界面:

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

And then I want to implement it as a class and the properties being set in the constructor:

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

  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);
    }
  }

However according to the compiler Request is not implementing the interface. I don't understand how does it check it, whilst it has everything filled according to the interface at the construction phase and if written in JavaScript this would work fine, type checking the same thing in Closure tools also works perfectly. The idea is that I want to implement the interface as a class so I can have utility methods in the prototype but still be able to easily convert to JSON string.

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

Any ideas?

有任何想法吗?

Thanks

谢谢

回答by Matthew Abbott

The language service will statically analyse your declaration of your interface, and because you've expressed that it requires that your headermember, that should form part of the class declaration:

语言服务将静态分析您的接口声明,并且因为您已经表示它需要您的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";
    }
}

Don't worry, the output javascript is a lot leaner:

别担心,输出 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;
})();