How to use getters/setters in TypeScript ?
Last Updated :
23 Jan, 2025
In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.
- Getters allow you to retrieve the value of a property with controlled logic.
- Setters enable controlled assignment to properties, often including validation or transformations.
JavaScript
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
set name(newName: string) {
if (newName.length > 0) {
this._name = newName;
}
}
}
const person = new Person("Alice");
console.log(person.name);
person.name = "Bob";
console.log(person.name);
- The get method allows controlled access to the _name property by returning its value.
- The set method enables controlled modification of the _name property, applying logic to ensure valid input.
Output:
Alice
Bob
1. Getter Method in TypeScript
A getter method in TypeScript is a special method that allows you to retrieve the value of an object's property in a controlled way. It is used to define how a property value is accessed.
- Getters provide a way to access private or protected class members without directly exposing them.
- The getter method can include logic to manipulate or validate the value before returning it.
Syntax:
get propertyName(): returnType {
// logic to return a value
}
- propertyName: The name of the property you want to access.
- returnType: The type of the value returned by the getter.
JavaScript
class Rectangle {
private _width: number;
private _height: number;
constructor(width: number, height: number) {
this._width = width;
this._height = height;
}
get area(): number {
return this._width * this._height;
}
}
const rectangle = new Rectangle(5, 10);
console.log(rectangle.area);
- The area getter method calculates the area of the rectangle and returns it whenever accessed.
- The area property is read-only because there is no setter method defined, providing a safe way to retrieve computed values without modification.
Output:
50
2. Setter Method in TypeScript
A setter method in TypeScript allows controlled modification of a class's property. It enables encapsulation by providing a mechanism to validate or manipulate data before assigning it to a private field.
- Setters are defined using the set keyword followed by the property name and a parameter representing the new value.
- They are useful for enforcing constraints or triggering side effects when a property value changes.
Syntax:
set propertyName(value: type) {
// logic to set the value
}
JavaScript
class Employee {
private _fullName: string = '';
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (newName && newName.length > 0) {
this._fullName = newName;
} else {
console.error('Invalid name.');
}
}
}
const employee = new Employee();
employee.fullName = 'John Doe';
console.log(employee.fullName);
employee.fullName = '';
- The Employee class has a private property _fullName to store the employee's name.
- The fullName getter retrieves the current value of _fullName.
- The fullName setter validates the newName to ensure it's a non-empty string before assigning it to _fullName. If the validation fails, it logs an error message.
Output:
John Doe
Invalid name.
More Example of Using Getter and Setter
Validating Age Property
JavaScript
class User {
private _age: number = 0;
get age(): number {
return this._age;
}
set age(value: number) {
if (value > 0 && value < 150) {
this._age = value;
} else {
console.error('Invalid age value');
}
}
}
const user = new User();
user.age = 25;
console.log(user.age);
user.age = -5;
- The User class has a private _age property to store the user's age.
- The age getter returns the current value of _age.
- The age setter validates the input to ensure it's within a realistic range (1 to 149) before assigning it to _age. If the input is invalid, an error message is logged.
Output:
25
Invalid age value
Full Name Property with Getter and Setter
JavaScript
class Person {
private _firstName: string = '';
private _lastName: string = '';
get fullName(): string {
return `${this._firstName} ${this._lastName}`;
}
set fullName(name: string) {
const parts = name.split(' ');
if (parts.length === 2) {
this._firstName = parts[0];
this._lastName = parts[1];
} else {
console.error('Invalid full name format');
}
}
}
const person = new Person();
person.fullName = 'John Doe';
console.log(person.fullName);
person.fullName = 'John';
- The Person class has private _firstName and _lastName properties.
- The fullName getter concatenates _firstName and _lastName to return the full name.
- The fullName setter splits the input string and assigns the parts to _firstName and _lastName. It expects exactly two parts; otherwise, it logs an error.
Output:
John Doe
Invalid full name format
Explore
TypeScript Tutorial
8 min read
TypeScript Basics
TypeScript primitive types
TypeScript Object types
TypeScript other types
TypeScript combining types
TypeScript Assertions
TypeScript Functions
TypeScript interfaces and aliases
TypeScript classes