我为我的服务结果创建了一个TypeScript
界面。现在我想为我的两个函数定义一个基本功能。问题是我收到了错误:
属性'ServiceResult'在'Support'类型的值上不存在。
我使用WebStorm
进行开发(VS2012
让我感到紧张,因为大型项目冻结 - 等待更好的整合:P)。
我是这样做的:
module Support {
export interface ServiceResult extends Object {
Error?: ServiceError;
Check?(): void;
GetErrorMessage?(): string;
}
}
Support.ServiceResult.prototype.Check = () => {
// (...)
};
Support.ServiceResult.prototype.GetErrorMessage = () => {
// (...)
};
我还尝试将原型移动到模块中,但同样的错误仍然存在......(当然我删除了Support.
前缀)。
答案 0 :(得分:4)
看起来您正在尝试向接口添加实现 - 这是不可能的。
您只能添加到实际的实现,例如类。您也可以决定只将实现添加到类定义中,而不是直接使用prototype
。
module Support {
export interface ServiceResult extends Object {
Error?: ServiceError;
Check?(): void;
GetErrorMessage?(): string;
}
export class ImplementationHere implements ServiceResult {
Check() {
}
GetErrorMessage() {
return '';
}
}
}
Support.ImplementationHere.prototype.Check = () => {
// (...)
};
Support.ImplementationHere.prototype.GetErrorMessage = () => {
// (...)
};
答案 1 :(得分:3)
您无法对接口进行原型设计,因为已编译的JavaScript根本不会发出与接口相关的任何内容。该接口纯粹用于编译时使用。看看这个:
这个TypeScript:
interface IFoo {
getName();
}
class Foo implements IFoo {
getName() {
alert('foo!');
}
}
编译为此JavaScript:
var Foo = (function () {
function Foo() { }
Foo.prototype.getName = function () {
alert('foo!');
};
return Foo;
})();
结果中根本没有IFoo
- 这就是您收到该错误的原因。通常,您不会对接口进行原型设计,您可以构建实现接口的类的原型。
您甚至不必自己编写原型,只需将接口实现为类就足够了,TypeScript编译器将为您添加原型。