BanksySan
BanksySan

Reputation: 28560

Interfaces and Getters\Setters

I have the following:

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

The interface looks to me to be implemented, however, running tsc throws an exception:

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

Upvotes: 1

Views: 123

Answers (2)

Tadwork
Tadwork

Reputation: 174

Interfaces in Typescript are great for defining the "shape" of the object you want. In your example you are looking for an object that has a property called type. This can be done by specifying:

interface IEngine {
    type: string;
}

The getters and setters are implementation details which are then defined in objects that implement the interface such the Engine type in your question.

Upvotes: 3

Yevgeniy.Chernobrivets
Yevgeniy.Chernobrivets

Reputation: 3194

You are implementing property, so in interface it should be like this:

interface IEngine {
    type:string;
}

Upvotes: 5

Related Questions