乐闻世界logo
搜索文章和话题

How to use get and set in typescript?

1个答案

1

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:

typescript
class 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:

  1. get fullName(): This get accessor allows us to retrieve a person's full name by combining _firstName and _lastName into a string.

  2. set lastName(name: string): This set accessor 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.

2024年6月29日 12:07 回复

你的答案