I would like to define an interface with a readonly property. For instance;
interface foo { get bar():bool; }
However, this gives the syntax error, "expected ';'" on bar. I have setup my VisualStudio to use the ES5 target, so getters are supported. Is this a limitation of interfaces? Might this change in the future; it is a very nice thing to be able to do.
In TypeScript, there are two supported methods getter and setter to access and set the class members.
Use the readonly modifier to declare a getter in an interface, e.g. interface Person {readonly name: string;} . Consumers of the interface will only be able to read the property, but they want be able to reassign it.
You cannot define instance fields in interfaces (unless they are constant - static final - values, thanks to Jon), since they're part of the implementation only. Thus, only the getter and setter are in the interface, whereas the field comes up in the implementation.
Typescript allows an interface to inherit from multiple interfaces.
Getter-only properties were introduced in Typescript 2.0:
interface foo { readonly bar: boolean; }
Yes, this is a limitation of interfaces. Whether or not the access to the property is implemented with a getter is an implementation detail and thus should not be part of the public interface. See also this question.
If you need a readonly attribute specified in an interface, you can add a getter method:
interface foo { getAttribute() : string; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With