我有以下界面:
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/