In TypeScript, accessors (getters and setters) are used to control the reading and writing of properties. You can define a getter to retrieve a property and a setter to modify a property, allowing you to add additional logic, such as validation, when setting a value.

Example: Accessors with Getter and Setter

class Employee {
  private _fullName: string;  // Private property
 
  // Getter for fullName
  get fullName(): string {
    return this._fullName;
  }
 
  // Setter for fullName with validation
  set fullName(newName: string) {
    const fullNameMaxLength = 10;
    if (newName && newName.length > fullNameMaxLength) {
      throw new Error("fullName has a max length of " + fullNameMaxLength);
    }
    this._fullName = newName;
  }
}
 
let employee = new Employee();
employee.fullName = "Bob Smith";  // Sets the fullName
if (employee.fullName) {  // Gets the fullName
  console.log(employee.fullName);
}

Key Points:

  1. Getter (get): A getter allows you to define how a property is read. In the example, get fullName(): string { return this._fullName; } retrieves the value of _fullName.
  2. Setter (set): A setter allows you to define how a property is set. In the example, set fullName(newName: string) checks whether the new name exceeds a maximum length before setting the value of _fullName.
  3. Validation in Setter: The setter can include custom logic, such as validating the input before assigning a value to the private property.