Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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.

like image 710
Ezward Avatar asked Oct 11 '12 17:10

Ezward


People also ask

Can we use getter and setter in TypeScript?

In TypeScript, there are two supported methods getter and setter to access and set the class members.

How do you define getter in interface TypeScript?

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.

CAN interface have getters and setters?

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.

Can TypeScript implement multiple interfaces?

Typescript allows an interface to inherit from multiple interfaces.


2 Answers

Getter-only properties were introduced in Typescript 2.0:

interface foo {     readonly bar: boolean; } 
like image 197
Vitaliy Ulantikov Avatar answered Sep 25 '22 02:09

Vitaliy Ulantikov


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; } 
like image 34
Valentin Avatar answered Sep 22 '22 02:09

Valentin