In TypeScript, get and set are known as accessors, which are special methods used to define object properties. The get method is used to access the value of a property, while the set method is used to set the value of a property. These methods are particularly useful when you want to add extra logic when accessing or modifying properties.
Here is an example of using get and set accessors in TypeScript:
typescriptclass Person { private _firstName: string; private _lastName: string; constructor(firstName: string, lastName: string) { this._firstName = firstName; this._lastName = lastName; } // Using get accessor to retrieve the full name get fullName(): string { return `${this._firstName} ${this._lastName}`; } // Using set accessor to set the last name, with additional logic such as validation set lastName(name: string) { if (name.length > 0) { this._lastName = name; } else { console.error('Invalid last name'); } } } let person = new Person('John', 'Doe'); // Accessing fullName via get accessor console.log(person.fullName); // Output: John Doe // Modifying last name via set accessor person.lastName = 'Smith'; console.log(person.fullName); // Output: John Smith // Attempting to set an invalid last name person.lastName = ''; // Output: Invalid last name
In the above example, we define a Person class with private properties _firstName and _lastName. We define two accessors for this class:
-
get fullName(): Thisgetaccessor allows us to retrieve a person's full name by combining_firstNameand_lastNameinto a string. -
set lastName(name: string): Thissetaccessor allows us to set a person's last name. Before setting the last name, we can add validation logic, such as checking if the new last name is empty, and if so, display an error message and reject the update.
By using get and set accessors, we can encapsulate the internal state of an object while providing a concise API to access and modify this state, as well as add validation or other necessary logic.