To add a getter to a class in TypeScript, simply define a method with the get
keyword followed by the property name.
Here's an example of a class with a getter:
index.ts143 chars12 lines
In this example, we have a Person
class with a private variable _name
, and a getter name
that returns the value of _name
.
To use this getter, we simply create a new Person
object and call the getter method:
index.ts79 chars3 lines
Note that we access the getter without parenthesis, as if it were a property of the object (me.name
instead of me.name()
). This is because getters are a special type of method that behave like object properties.
gistlibby LogSnag