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.