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

Loading Code Playground...

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`).