[英]Implementing prototypes for interfaces in TypeScript
I have created a TypeScript
interface for my service results. 我为我的服务结果创建了一个TypeScript
接口。 Now I want to define a basic functionality for both my functions inside. 现在我想为我的两个函数定义一个基本功能。 The problem is I get an error: 问题是我收到一个错误:
The property 'ServiceResult' does not exist on value of type 'Support'. 属性“ServiceResult”在“支持”类型的值上不存在。
I use WebStorm
for development ( VS2012
makes me nervous because on freezes by large projects - waiting for better integration:P). 我使用WebStorm
进行开发( VS2012
让我感到紧张,因为大型项目冻结 - 等待更好的集成:P)。
Here's how I do it: 我是这样做的:
module Support {
export interface ServiceResult extends Object {
Error?: ServiceError;
Check?(): void;
GetErrorMessage?(): string;
}
}
Support.ServiceResult.prototype.Check = () => {
// (...)
};
Support.ServiceResult.prototype.GetErrorMessage = () => {
// (...)
};
I have also tried to move my prototypes into the module, but same error still... (of course I removed Support.
prefix). 我也尝试将原型移动到模块中,但同样的错误仍然存在......(当然我删除了Support.
前缀)。
It looks like you are trying to add implementation to an interface - which isn't possible. 看起来您正在尝试向接口添加实现 - 这是不可能的。
You can only add to a real implementation, for example a class. 您只能添加到实际的实现,例如类。 You may also decide to just add the implementation to the class definition rather than directly using prototype
. 您也可以决定只将实现添加到类定义中,而不是直接使用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 = () => {
// (...)
};
You can't prototype an interface because the compiled JavaScript does not emit anything related to the interface at all. 您无法对接口进行原型设计,因为已编译的JavaScript根本不会发出与接口相关的任何内容。 The interface exists purely for compile-time use. 该接口纯粹用于编译时使用。 Take a look at this: 看看这个:
This TypeScript: 这个TypeScript:
interface IFoo {
getName();
}
class Foo implements IFoo {
getName() {
alert('foo!');
}
}
Compiles to this JavaScript: 编译到这个JavaScript:
var Foo = (function () {
function Foo() { }
Foo.prototype.getName = function () {
alert('foo!');
};
return Foo;
})();
There is no IFoo
in the result, at all - which is why you are getting that error. 结果中根本没有IFoo
- 这就是你得到错误的原因。 Typically you wouldn't prototype an interface, you would prototype a class that implements your interface. 通常,您不会对接口进行原型设计,您将构建实现接口的类的原型。
You don't even have to write the prototype yourself, just implementing the interface as a class is enough and the TypeScript compiler will add the prototype for you. 您甚至不必自己编写原型,只需将接口实现为类就足够了,TypeScript编译器将为您添加原型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.