接口和Getters\Setters

Ban*_*San 1 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';
Run Code Online (Sandbox Code Playgroud)

界面看起来我要实现,但是,运行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; }'.
Run Code Online (Sandbox Code Playgroud)

小智 5

你正在实现属性,所以在界面中它应该是这样的:

interface IEngine {
    type:string;
}
Run Code Online (Sandbox Code Playgroud)