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

前端 未结 4 846
青春惊慌失措
青春惊慌失措 2020-12-14 14:01

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

interface I {
      get name():string;
}

cl         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 14:32

    First of all, Typescript only supports get and set syntax when targetting Ecmascript 5. To achieve this, you have to call the compiler with

    tsc --target ES5
    

    Interfaces do not support getters and setters. To get your code to compile you would have to change it to

    interface I { 
        getName():string;
    }
    
    class C implements I { 
        getName():string {
              return null;
        }   
    }
    

    What typescript does support is a special syntax for fields in constructors. In your case, you could have

    interface I {
        getName():string;
    }
    
    class C implements I {
        constructor(public name: string) {
        }
        getName():string {
            return name;
        }
    }
    

    Notice how class C does not specify the field name. It is actually declared using syntactic sugar public name: string in the constructor.

    As Sohnee points out, the interface is actually supposed to hide any implementation details. In my example, I have chosen the interface to require a java-style getter method. However, you can also a property and then let the class decide how to implement the interface.

提交回复
热议问题