javascript - 接口(interface)和 Getters\Setters

标签 javascript typescript

我有以下内容:

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';

接口(interface)在我看来已经实现,但是,运行 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)中它应该是这样的:

interface IEngine {
    type:string;
}

关于javascript - 接口(interface)和 Getters\Setters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36701827/

相关文章:

angular - 类型 'wakeLock' 上不存在属性 'Navigator'

来自@types 中声明的命名空间的 typescript 扩展接口(interface)

javascript - ng bootstrap 4 - typeahead 打开焦点

javascript - 为什么 fetch 会返回 "TypeError: Failed to fetch"而不仅仅是 "Failed to fetch"?

javascript - 没有换页的粘性页脚

javascript - AngularJS:如何使用 $filter 从对象数组中查找对象,给定数组中的属性值数组

javascript - 使用 ion-item 在 NTH 元素后添加 Item

javascript - ReactJs/Typescript 如何将对象数组传递到界面 Prop 中?

javascript - 如何在 Typescript 中进行后期绑定(bind)

javascript - 关节.shapes.uml.js : Uncaught TypeError: Cannot read property 'Generic' of undefined