In TypeScript, get and set accessors allow us to effectively encapsulate properties within objects, enabling additional logic to be executed when reading or writing properties. The get accessor defines how to read the property value, while the set accessor defines how to set the property value. Below is an example using get and set accessors:
typescriptclass Person { private _firstName: string; private _lastName: string; constructor(firstName: string, lastName: string) { this._firstName = firstName; this._lastName = lastName; } // Using the get accessor to read fullName get fullName(): string { return `${this._firstName} ${this._lastName}`; } // Using the set accessor to set firstName and lastName set fullName(name: string) { const parts = name.split(' '); if (parts.length !== 2) { throw new Error('Please enter a full name, e.g., John Doe'); } this._firstName = parts[0]; this._lastName = parts[1]; } } let person = new Person('John', 'Doe'); // Accessing fullName via the get accessor console.log(person.fullName); // Output: John Doe // Modifying fullName via the set accessor person.fullName = 'Jane Smith'; // Accessing the modified fullName via the get accessor console.log(person.fullName); // Output: Jane Smith
In the above example, the Person class has two private properties _firstName and _lastName. To control access to these properties, we define a fullName property with a get accessor and a set accessor.
- The
get fullName()method is used to assemble and return a full name when needed, combining_firstNameand_lastName. - The
set fullName(name: string)method allows us to set_firstNameand_lastNamevia a string. If the input string does not consist of two parts, it throws an error.
This allows us to encapsulate the implementation details of properties using object-oriented principles, while providing a simple interface for external code to use via accessors. The benefit is that we can add validation logic or other additional operations when setting or getting properties without exposing the internal structure of the class.