#typescript
#oop
#classes
Day 9: Access Modifiers
Controlling Visibility
Welcome to Day 9! Classes are great, but sometimes you want to keep secrets. That’s where Access Modifiers come in.
The Three Modifiers
1. public (Default)
Accessible from anywhere. If you don’t specify a modifier, it defaults to public.
class Animal {
public name: string; // Same as just `name: string`
}
2. private
Accessible only within the class. Not accessible from instances or subclasses.
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
getBalance() {
return this.balance; // OK, inside class
}
}
const account = new BankAccount(100);
// console.log(account.balance); // Error! Private member.
3. protected
Accessible within the class and classes that inherit from it (subclasses). We’ll see this in action tomorrow with Inheritance.
Parameter Properties (Shorthand)
TypeScript has a wonderful shortcut for declaring and assigning properties in the constructor.
The Long Way:
class User {
public name: string;
private id: string;
constructor(name: string, id: string) {
this.name = name;
this.id = id;
}
}
The Short Way (Parameter Properties):
class User {
constructor(public name: string, private id: string) {}
}
This does the exact same thing! It declares the property and assigns the value.
Challenge for Today
- Refactor your
Calculatorclass from yesterday. - Add a
privatepropertyhistory(an array of strings). - Every time a calculation is done, push a string like “Added 5 and 10” to the history.
- Add a
publicmethodgetHistory()that returns the history array. - Verify you cannot access
historydirectly from the instance.
See you on Day 10 for Inheritance!