Getters and Setters in TypeScript

In TypeScript, getter and setter are special kinds of functions that can be used to access or modify the values of class properties. They allow developers to intercept the reading and writing of object properties and execute custom logic when the properties are read or updated. This feature is commonly used for data validation, data transformation, and encapsulation. In this article, we’ll explore the basics of getters and setters in TypeScript and how to use them in your code.

Accessor Methods in TypeScript

Accessor methods are a special kind of method that allow developers to define how properties can be accessed and modified. These methods are identified using the keywords `get` and `set`. To create an accessor method, we define a function with the `get` keyword to access a property, and a function with the `set` keyword to modify it.

Here’s an example:

“`
class Person {
private _name: string;

get name() {
return this._name;
}

set name(value: string) {
if (value.length < 3) {
throw new Error(‘Name must have at least 3 characters’);
}
this._name = value;
}
}
“`

In this example, we create a `Person` class with a private property `_name`. We then define a `get` method to access the `_name` property and a `set` method to modify it. The `set` method validates that the input value has at least three characters before assigning it to the `_name` property. If the input value does not meet the validation criteria, the method throws an error.

Using Accessor Methods

To use accessor methods in TypeScript, we can simply call them like regular properties. For example:

“`
const john = new Person();
john.name = ‘Jo’;
console.log(john.name); // throws “Name must have at least 3 characters” error
john.name = ‘John’;
console.log(john.name); // outputs “John”
“`

In this example, we create a new `Person` object called `john`. We then attempt to set its `name` property to `’Jo’`, which fails the validation criteria and throws an error. We then set the `name` property to `’John’`, which passes the validation and updates the `_name` property to `’John’`. When we log the `name` property, it outputs `’John’`.

Benefits of Accessor Methods

The use of accessor methods provides several benefits in software development:

  • Encapsulation: Accessor methods allow developers to hide implementation details from other parts of the code. For example, a getter method can be used to retrieve a value from a class property without exposing the underlying data structure.
  • Data Validation: Accessor methods can be used to enforce data validation rules in real-time. For example, a setter method can validate input data and throw an error if the data is invalid.
  • Data Transformation: Accessor methods can be used to transform data before and after it is read or written. For example, a getter method can transform a string value to an uppercase format before returning it.
  • Code Reusability: Accessor methods can be reused across multiple classes and objects without the need for additional code.

FAQs

What is the difference between a getter and a setter method?

A getter method is used to retrieve a value from a class property, while a setter method is used to modify it. Both methods are identified using the keywords `get` and `set`, respectively. Getter methods have no input parameters, while setter methods receive a single parameter representing the new value to be set.

Can I use access modifiers with accessor methods?

Yes, accessor methods can have access modifiers (public, private, protected) just like regular properties and methods. The access modifier is applied to the underlying property, not to the accessor method. For example:

“`
class Person {
private _age: number;

public get age() {
return this._age;
}

public set age(value: number) {
if (value < 0 || value > 120) {
throw new Error(‘Age must be between 0 and 120’);
}
this._age = value;
}
}
“`

In this example, we use the `private` access modifier to make the `_age` property inaccessible outside the `Person` class. We then define a `get` method and a `set` method with the `public` access modifier to allow external code to read and modify the `age` property, respectively.

Can I use getter and setter methods in interfaces?

Yes, you can use getter and setter methods in TypeScript interfaces. However, the interface must declare the signature of the accessor methods, not the underlying properties. For example:

“`
interface IPerson {
readonly name: string;
age: number;
getName(): string;
setName(name: string): void;
getAge(): number;
setAge(age: number): void;
}
“`

In this example, we define an `IPerson` interface with two read-only properties (`name`), two accessor methods (`age`), and two regular methods (`getName` and `getAge`). The accessor methods are defined with the `get` and `set` keywords, and their signature matches the `Person` class example above.

Similar Posts