add a getter to a class in typescript

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.ts
class Person {
  private _name: string;

  constructor(name: string) {
    this._name = name;
  }

  get name() {
    return this._name;
  }
}
143 chars
12 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.ts
const me = new Person('John Doe');
console.log(me.name); // Output: 'John Doe'
79 chars
3 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