0
0
Typescriptprogramming~3 mins

Why Getter and setter with types in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could stop bugs caused by wrong data updates with just a simple code trick?

The Scenario

Imagine you have an object representing a person, and you want to control how their age is accessed and changed. Without getters and setters, you have to manually check and update the age everywhere in your code.

The Problem

Manually checking and updating values everywhere is slow and easy to forget. It can cause bugs if you accidentally set invalid ages or read outdated data. This makes your code messy and hard to maintain.

The Solution

Getters and setters let you control how properties are read and written in one place. With types, you ensure only valid data is used, catching mistakes early and keeping your code clean and safe.

Before vs After
Before
person.age = -5; // no check, can cause errors
console.log(person.age);
After
private _age: number = 0;

set age(value: number) { if(value >= 0) this._age = value; }
get age(): number { return this._age; }
What It Enables

It enables safe, clear, and typed control over object properties, preventing errors and making your code easier to understand and maintain.

Real Life Example

In a user profile, you can use getters and setters with types to ensure the user's age is always a positive number, avoiding invalid data that could break your app.

Key Takeaways

Manual property handling is error-prone and scattered.

Getters and setters centralize control with type safety.

This leads to cleaner, safer, and more maintainable code.