Web Analytics

Access Modifiers

Beginner~20 min

Access modifiers control the visibility of class members. TypeScript provides three modifiers: public, private, and protected for proper encapsulation.

TypeScript Access Modifiers

Access Modifiers

Output
Click Run to execute your code
Default: If no modifier is specified, members are public by default.

Modifier Comparison

Modifier Same Class Child Class Outside
public โœ“ โœ“ โœ“
protected โœ“ โœ“ โœ—
private โœ“ โœ— โœ—

When to Use Each Modifier

  • public: API methods, properties meant to be accessed externally
  • private: Internal implementation details, sensitive data
  • protected: Properties/methods for inheritance hierarchy

Common Mistakes

1. Making Everything Public

// โœ— Poor encapsulation
class User {
    public password: string;  // Exposed!
    public internalId: number;  // Should be private
}

// โœ“ Proper encapsulation
class User {
    private password: string;
    private internalId: number;
    public userName: string;
}

2. Using Private When Protected is Needed

class Animal {
    private makeSound() {}  // โœ— Child can't override
}

class Dog extends Animal {
    makeSound() {}  // Error!
}

// โœ“ Use protected for inheritance
class Animal {
    protected makeSound() {}
}
Note: TypeScript access modifiers are compile-time only. They don't exist in JavaScript runtime.

Summary

  • public: Accessible everywhere (default)
  • private: Only within the same class
  • protected: Same class + child classes
  • Use private for sensitive data and internal logic