TypeScript Course
TypeScript
/
Intermediate

Public, Private, Protected

Definition

Keywords that control the visibility and accessibility of class properties and methods from outside the class.

Explain Like I'm New

`public` (the default) means anyone can see and change it. `private` means it is locked inside the class vault; nobody outside can touch it, not even child classes. `protected` means it is locked to outsiders, but 'family members' (classes that inherit from it) get a copy of the key.

Real World Example

Making an API key property `private` so that a junior developer cannot accidentally `console.log(apiService.apiKey)` elsewhere in the application.

Common Use Cases

  • •Encapsulation
  • •Hiding internal implementation details from consumers

Interactive Example

class BankAccount {
  public accountHolder: string;
  private pinCode: number; // TS blocks access from outside
  protected balance: number; // Accessible by children

  constructor(name: string, pin: number, balance: number) {
    this.accountHolder = name;
    this.pinCode = pin;
    this.balance = balance;
  }
}

class SavingsAccount extends BankAccount {
  addInterest() {
    // Valid: 'balance' is protected
    this.balance += 100; 
    
    // ERROR: 'pinCode' is private. Not even child can see it.
    // console.log(this.pinCode); 
  }
}

const account = new BankAccount("Alice", 1234, 1000);
console.log(account.accountHolder); // Valid (Public)
// console.log(account.balance); // ERROR (Protected, outsiders blocked)
// console.log(account.pinCode); // ERROR (Private, outsiders blocked)

Interview Questions

basic

  • Which access modifier is the default if none is provided?

intermediate

  • What is the difference between `private` and `protected`?

advanced

  • Are TS `private` modifiers actually private at runtime in JavaScript?

Flash Cards

Question

Private vs Protected?

Click to reveal answer
Answer

`private` properties cannot be accessed by classes that `extend` the parent class. `protected` properties CAN be accessed by child classes via the `this` keyword, but still block outside access.

Question

Are they private at runtime?

Click to reveal answer
Answer

NO! TypeScript modifiers are 100% erased during compilation. At runtime, a `private` property is completely public and can be accessed/hacked. If you need true runtime privacy, you must use modern ES6 `#` private fields (e.g., `#apiKey`).