Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Encapsulation

Learn how encapsulation protects an object's internal data and controls how that data can be accessed or modified in TypeScript.

Simple Explanation: Encapsulation means keeping data and related methods together in a class while controlling access to internal data. TypeScript access modifiers such as private and public help implement encapsulation.

1. What is Encapsulation?

Encapsulation is an important Object-Oriented Programming (OOP) concept. It allows a class to manage its internal data and expose only the operations that should be available to other parts of the application.

For example, in a bank account application, the account balance should not be changed arbitrarily. The class can provide methods to deposit or withdraw money while validating the requested amount.

Main Components

🔒
Private Data

Restricts direct access to class members from outside the class.

⚙️
Public Methods

Provide controlled operations for working with internal data.

✅
Validation

Checks values before modifying the object's internal state.

2. Encapsulation Workflow Diagram

Understand how an application requests an operation without directly modifying the object's private data.

👤
User / Application

Requests an operation such as depositing money.

→
⚙️
Public Method

Receives the request and validates the input.

→
🔒
Private Data

Changes only when the permitted operation succeeds.

→
✅
Result

The application receives the result or current balance.

Remember: Encapsulation controls how the object's data is accessed and updated. It helps enforce rules and maintain valid object state.

3. Using Private Properties

The private modifier restricts access to a class member from outside that class during TypeScript type checking. The class's own methods can still access and update the member.

Example

class Employee {
    private salary: number = 30000;

    displaySalary(): void {
        console.log("Salary: " + this.salary);
    }
}

const emp1 = new Employee();

emp1.displaySalary();

Expected Output

Salary: 30000

Understanding the Code

Code Purpose
private salary: number Declares a private salary property.
this.salary Accesses salary from within the Employee class.
emp1.displaySalary() Calls the public method to display salary.
Important: TypeScript's private modifier is primarily enforced by the type checker. It is not the same as JavaScript's runtime-private #field syntax.

4. Controlling Data with Public Methods

Instead of exposing a property for direct modification, a class can provide public methods that validate values before changing private data.

Example: Bank Account

class BankAccount {
    private balance: number = 1000;

    deposit(amount: number): void {
        if (amount <= 0) {
            console.log("Invalid deposit amount");
            return;
        }

        this.balance += amount;
        console.log("Deposit successful");
    }

    getBalance(): number {
        return this.balance;
    }
}

const account = new BankAccount();

account.deposit(500);
console.log("Balance: " + account.getBalance());

Expected Output

Deposit successful
Balance: 1500

The balance starts at 1000. The deposit method accepts the valid amount of 500 and updates the private balance to 1500.

Key Point: The application cannot assign to account.balance directly during normal TypeScript type checking because the property is private. It uses the class's public methods instead.

5. Validation Inside Encapsulation

A class can reject invalid values before updating its private properties. This helps prevent invalid data from entering the object's state.

Example: Student Age

class Student {
    private age: number = 0;

    setAge(age: number): void {
        if (age <= 0 || age > 120) {
            console.log("Invalid age");
            return;
        }

        this.age = age;
        console.log("Age updated");
    }

    getAge(): number {
        return this.age;
    }
}

const student1 = new Student();

student1.setAge(22);
console.log("Age: " + student1.getAge());

student1.setAge(-5);
console.log("Age: " + student1.getAge());

Expected Output

Age updated
Age: 22
Invalid age
Age: 22

Validation Workflow

📥
Input

Receive an age value.

→
🔍
Validate

Check whether age is greater than 0 and at most 120.

→
✅
Valid

Update the private age property.

→
🛑
Invalid

Reject the value and preserve the existing age.

6. Getters and Setters

TypeScript supports get and set accessors. A getter reads a value, while a setter provides controlled assignment. They are useful for validating data when properties are accessed or changed.

Example

class Product {
    private _price: number = 0;

    get price(): number {
        return this._price;
    }

    set price(value: number) {
        if (value < 0) {
            console.log("Price cannot be negative");
            return;
        }

        this._price = value;
    }
}

const product1 = new Product();

product1.price = 500;
console.log(product1.price);

product1.price = -100;
console.log(product1.price);

Expected Output

500
Price cannot be negative
500

Getter and Setter Diagram

✍️
Assign Value

product1.price = 500

→
🔍
Setter

Checks whether the price is valid.

→
💾
Private Field

Stores the accepted value in _price.

→
📖
Getter

product1.price reads the stored value.

Remember: Use product1.price, not product1.price(), to access a getter or assign a value through a setter.

7. Advantages of Encapsulation

Controlled Access

Controls how other parts of the application interact with internal data.

Data Validation

Allows invalid values to be rejected before updating internal state.

Maintainability

Keeps data-related rules and operations organized inside a class.

Reduced Dependencies

Other code can use public operations without depending on internal implementation details.

Summary

Encapsulation groups data and related operations inside a class and controls access to internal members. TypeScript's private modifier restricts direct access during type checking, while public methods, getters and setters can validate and manage changes to internal data.

Next, learn TypeScript access modifiers: public, private and protected.