Emulating abstract properties on a TypeScript class. TypeScript does not have 'abstract' classes as such. But because of structural typing, interfaces are somewhat weak. One cannot for example assert that x instanceof Y, when Y is an interface. However I've noticed that a class field that is not initialised in a constructor behaves already. TypeScript interface provides a distinct feature to define optional properties. An object which implements this interface need not to define these properties. This feature differentiate TypeScript interface with other OOPS languages interfaces like C# in which all members must be implement by class.
At the moment, TypeScript
does not allow use get/set methods(accessors) in interfaces.For example:
furthermore, TypeScript does not allow use Array Function Expression in class methods:for ex.:
Is there any other way I can use a getter and setter on an interface definition?
4 Answers
You can specify the property on the interface, but you can't enforce whether getters and setters are used, like this:
In this example, the interface doesn't force the class to use getters and setters, I could have used a property instead (example below) - but the interface is supposed to hide these implementation details anyway as it is a promise to the calling code about what it can call.
And lastly, =>
is not allowed for class methods - you could start a discussion on Codeplex if you think there is a burning use case for it. Here is an example:
To supplement the other answers, if your desire is to define a get value
on an interface, you can do this:
![Virtual vs abstract class Virtual vs abstract class](http://joelleach.net/wp-content/uploads/2016/11/typescript.png)
but as far as I'm aware, and as others mentioned, there is no way currently to define a set-only property in the interface. You can, however, move the limitation to a run-time error (useful during the development cycle only):
Not recommended practice; but an option.
First of all, Typescript only supports get
and set
syntax when targetting Ecmascript 5. To achieve this, you have to call the compiler with
Interfaces do not support getters and setters. To get your code to compile you would have to change it to
What typescript does support is a special syntax for fields in constructors. In your case, you could have
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.
Using TypeScript 3.4:
See example on TypeScript Playground.