Classes & Visibility
Public, Private, and Protected modifiers.
Object-Oriented Encapsulation
TypeScript provides class visibility modifiers:
public (default) - accessible anywhere.
protected - accessible within the class and subclasses.
private - accessible *only* within the class.
Hiding State
Visibility modifiers help you hide internal implementation details.
If you have a DatabaseConnection class, you shouldn't let outside code directly mutate the connectionString or socket properties. You mark them as private to force usage through safe methods.
Syntax
typescript
class User {
public name: string;
private token: string;
constructor(name: string, token: string) {
this.name = name;
this.token = token;
}
}
const user = new User("Alice", "secret123");
console.log(user.name); // OK
// console.log(user.token); // TypeScript Error!
Try it
Attempt to access a private property versus a #private property from outside the class. Observe how the compiler reacts compared to the actual JavaScript runtime engine.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
public,protected, andprivatecontrol access levels.- These modifiers only exist at compile time in TypeScript.
- For strict runtime privacy, use the native JS
#syntax. - Parameter properties in constructors save a lot of boilerplate.
Done with this concept?
Mark it complete to track your progress. No login needed.