The getter method is used when you want to access a property of an object whereas, setter method is used to set or change a value of a property of an object.

Typescript uses get keyword to declare a getter method and set keyword to declare a setter method.

class Animal {
  private weight: number;

  get myWeight() {
    return this.weight;
  }

  set myWeight(weight: number) {
    if (weight > 0) {
      this.weight = weight;
      return;
    }
    console.log("Invalid weight");
  }
}

let animal = new Animal();

animal.myWeight = 10;

console.log(animal.myWeight); // 10

In the above example, we have a getter method get myWeight() which simply returns the value of private property weight. To access weight we can simply write:

animal.myWeight; // 10

Similarly, we also have a setter method set myWeight() which takes in one parameter, that is the value we want the method to set to weight property. In this case, we are checking if the value of weight is a positive number before assigning it to the weight property. You can assign the value as shown below:

animal.myWeight = 10;

Using underscore(_)

As a convention, we can make use of _ while naming a property. This can help us identify whether a given property is private and is not accessible from outside of the class.

We can write the above class using the underscore(_) as follows:

class Animal {
  private _weight: number;

  get weight() {
    return this._weight;
  }

  set weight(weight: number) {
    if (weight > 0) {
      this._weight = weight;
      return;
    }
    console.log("Invalid weight");
  }
}

let animal = new Animal();

animal.weight = 10;

console.log(animal.weight); // 10