Interfaces and GettersSetters
Interfaces and GettersSetters
我有以下内容:
interface IEngine {
type():string;
type(type:string):void;
}
class Engine implements IEngine {
private _type: string;
get type():string {
return this._type;
}
set type(type:string) {
this._type = type;
}
}
var engine = new Engine();
engine.type = 'foo';
在我看来,这个接口已经实现了,但是,运行tsc会抛出一个异常:
F:'>tsc interfaces.ts --target "es5"
interfaces.ts(11,7): error TS2420: Class 'Engine' incorrectly implements interface 'IEngine'.
Types of property 'type' are incompatible.
Type 'string' is not assignable to type '{ (): string; (type: string): void; }'.
您正在实现属性,所以在接口中应该是这样的:
interface IEngine {
type:string;
}
Typescript中的接口非常适合定义所需对象的"形状"。在您的示例中,您正在查找一个具有名为type
的属性的对象。这可以通过指定来完成:
interface IEngine {
type: string;
}
getter和setter是实现细节,然后在实现接口的对象中定义,例如问题中的Engine
类型。
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JSON and jQuery Search
- Flash and External Javascript
- Interfaces and GettersSetters