#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

  1. Refactor your Calculator class from yesterday.
  2. Add a private property history (an array of strings).
  3. Every time a calculation is done, push a string like “Added 5 and 10” to the history.
  4. Add a public method getHistory() that returns the history array.
  5. Verify you cannot access history directly from the instance.

See you on Day 10 for Inheritance!