Part 2: Encapsulation and Access Modifiers - Data Protection
Introduction
The Problem: Direct Property Access
class BankAccount {
balance: number; // Public by default - anyone can modify!
constructor(initialBalance: number) {
this.balance = initialBalance;
}
withdraw(amount: number): void {
if (amount > this.balance) {
throw new Error('Insufficient funds');
}
this.balance -= amount;
}
}
const account = new BankAccount(1000);
// Problem: Can bypass validation!
account.balance = -500; // Direct modification - no validation!
console.log(account.balance); // -500
// Or accidentally overwrite
account.balance = undefined; // Oops!The Solution: Encapsulation
Access Modifiers in TypeScript
Public (Default)
Private
Protected
Getters and Setters
Basic Getters and Setters
Computed Properties
Real Example: User Profile Management
Information Hiding
Exposing Only What's Needed
Internal State Management
Real Example: Shopping Cart
Private Fields (#) - ES2022 Feature
Best Practices
1. Make Everything Private by Default
2. Use Getters for Computed Values
3. Validate in Setters
4. Immutable Objects
What's Next
PreviousPart 1: Classes and Objects - Building BlocksNextPart 3: Inheritance and Polymorphism - Code Reuse and Flexibility
Last updated