Ezward Ezward - 6 months ago 25
TypeScript Question

Is it possible to use getters/setters in TypeScript Interfaces?

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.

Answer Source

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