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?