add a setter to a class in typescript

In TypeScript, you can add a setter to a class using the set keyword followed by the name of the property you want to set.

Here's an example that demonstrates how to add a setter to a class:

index.ts
class Person {
  private _age: number;

  get age(): number {
    return this._age;
  }

  set age(value: number) {
    if (value < 0 || value > 120) {
      throw new Error('Invalid age.');
    }
    this._age = value;
  }
}
226 chars
15 lines

In the example above, we define a Person class with a private _age property. We then define a getter and a setter for the age property.

The get age() method returns the value of the _age property, while the set age(value: number) method sets the value of _age if it falls within a valid range (between 0 and 120 in this example).

To set the age of a Person object, we can simply assign a value to the age property:

index.ts
const person = new Person();
person.age = 30;
console.log(person.age); // Output: 30
85 chars
4 lines

Note that if we try to assign an invalid age (e.g. a negative number or a number greater than 120), the setter will throw an error.

gistlibby LogSnag