Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 接口和getter\setter_Javascript_Typescript - Fatal编程技术网

Javascript 接口和getter\setter

Javascript 接口和getter\setter,javascript,typescript,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 = typ

我有以下资料:

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

您正在实现属性,所以在接口中应该是这样的:

interface IEngine {
    type:string;
}

Typescript中的接口非常适合定义所需对象的“形状”。在您的示例中,您正在查找具有名为
type
的属性的对象。这可以通过指定以下内容来实现:

interface IEngine {
    type: string;
}

getter和setter是实现细节,然后在实现接口的对象中定义这些细节,例如问题中的
引擎
类型。

Typescript中的接口非常适合定义所需对象的“形状”。在您的示例中,您正在查找具有名为
type
的属性的对象。这可以通过指定以下内容来实现:

interface IEngine {
    type: string;
}
getter和setter是实现细节,然后在实现接口的对象中定义,如您问题中的
引擎
类型