How to use getters/setters in TypeScript ? (original) (raw)

Last Updated : 23 Jan, 2025

In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.

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);

`

**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.

**Syntax:

get propertyName(): returnType {
// logic to return a value
}

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);

`

**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.

**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 = '';

`

**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;

`

**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';

``

**Output:

John Doe
Invalid full name format