TypeScript Access Modifiers
Access modifiers control which parts of your code can access a class's properties and methods. TypeScript supports `public`, `private`, and `protected`, giving you control over encapsulation.
By default, all class members are `public`, meaning they can be accessed from anywhere. Marking something `private` restricts access to inside the class only, while `protected` allows access in the class and its subclasses.
class Account {
private balance: number = 0;
public owner: string;
}public and private
`public` members (the default) can be accessed from anywhere. `private` members can only be accessed inside the class where they are defined, not from outside or from subclasses.
protected
`protected` members behave like private but are also accessible from subclasses, making them useful for values that subclasses need to use internally but outside code should not touch.
class Account {
private balance: number = 0;
deposit(amount: number): void {
this.balance += amount;
}
getBalance(): number {
return this.balance;
}
}
const acc = new Account();
acc.deposit(100);
console.log(acc.getBalance());100balance is private, so it can only be changed through the class's own methods like deposit().
class Animal {
protected sound: string = "...";
makeSound(): string {
return this.sound;
}
}
class Dog extends Animal {
constructor() {
super();
this.sound = "Woof";
}
}
console.log(new Dog().makeSound());Woofsound is protected, so the Dog subclass can access and change it, but outside code cannot.
Key points
- public members are accessible from anywhere (the default).
- private members are only accessible inside the same class.
- protected members are accessible in the class and its subclasses.
- Access modifiers help enforce encapsulation and safer class design.
