0
0
Typescriptprogramming~5 mins

Getter and setter with types in Typescript

Choose your learning style9 modes available
Introduction

Getters and setters let you control how to read and change a value in an object. They help keep data safe and correct.

When you want to check or change a value before saving it.
When you want to hide how a value is stored inside an object.
When you want to run some code automatically when a value is read or changed.
When you want to make a property look like a normal variable but control its access.
When you want to add types to the values you get or set for safety.
Syntax
Typescript
class ClassName {
  private _propertyName: Type;

  get propertyName(): Type {
    // return the value
  }

  set propertyName(value: Type) {
    // set the value
  }
}

Use get before a method to make it a getter.

Use set before a method to make it a setter. The setter must have exactly one parameter.

Examples
This example shows a getter and setter for a name property with type string. The setter trims spaces.
Typescript
class Person {
  private _name: string = '';

  get name(): string {
    return this._name;
  }

  set name(value: string) {
    this._name = value.trim();
  }
}
This example only allows setting count to zero or positive numbers.
Typescript
class Counter {
  private _count: number = 0;

  get count(): number {
    return this._count;
  }

  set count(value: number) {
    if (value >= 0) {
      this._count = value;
    }
  }
}
Sample Program

This program creates a bank account with a balance. The setter checks that the balance is not negative before changing it. It prints the balance before and after trying to set a negative value.

Typescript
class BankAccount {
  private _balance: number = 0;

  get balance(): number {
    return this._balance;
  }

  set balance(amount: number) {
    if (amount >= 0) {
      this._balance = amount;
    } else {
      console.log('Balance cannot be negative');
    }
  }
}

const account = new BankAccount();
account.balance = 100;
console.log(`Balance is: $${account.balance}`);
account.balance = -50; // tries to set negative balance
console.log(`Balance is still: $${account.balance}`);
OutputSuccess
Important Notes

Getters and setters look like normal properties when used, but they run code behind the scenes.

Always type the getter return and setter parameter for safety and clarity.

Setters cannot return a value; they only set the property.

Summary

Getters and setters let you control how properties are read and changed.

Use types to make sure values are correct.

They help keep your data safe and your code clean.