interfacegetsetaccessortypescript

Is it possible to use getters/setters in interface definition?


At the moment, TypeScript does not allow use get/set methods(accessors) in interfaces. For example:

interface I {
      get name(): string;
}

class C implements I {
      get name(): string {
          return null;
      } 
}

furthermore, TypeScript does not allow using arrow function expressions in class methods, for example:

class C {
    private _name: string;

    get name(): string => this._name;
}

Is there any other way I can use a getter and setter on an interface definition?


Solution

  • You can specify the property on the interface, but you can't enforce whether getters and setters are used, like this:

    interface IExample {
        Name: string;
    }
    
    class Example implements IExample {
        private _name: string = "Bob";
    
        public get Name() {
            return this._name;
        }
    
        public set Name(value) {
            this._name = value;
        }
    }
    
    var example = new Example();
    alert(example.Name);
    

    In this example, the interface doesn't force the class to use getters and setters, I could have used a property instead (example below) - but the interface is supposed to hide these implementation details anyway as it is a promise to the calling code about what it can call.

    interface IExample {
        Name: string;
    }
    
    class Example implements IExample {
        // this satisfies the interface just the same
        public Name: string = "Bob";
    }
    
    var example = new Example();
    alert(example.Name);
    

    And lastly, => is not allowed for class methods - you could start a discussion on Codeplex if you think there is a burning use case for it. Here is an example:

    class Test {
        // Yes
        getName = () => 'Steve';
    
        // No
        getName() => 'Steve';
    
        // No
        get name() => 'Steve';
    }