DEV Community

Jeferson Eiji
Jeferson Eiji

Posted on • Originally published at dev.to

Mastering Classes and Access Modifiers in TypeScript: Public, Private, Protected Explained

TypeScript offers robust support for object-oriented programming with classes, interfaces, and access modifiers. Understanding how to define and secure your class properties is key to writing maintainable and safe code.

Access Modifiers in TypeScript

  • public (default): Property or method can be accessed from anywhere.
  • private: Access is limited to within the class itself.
  • protected: Accessible in the class and its subclasses, but not from outside.

Example: Defining a Class with Access Modifiers

class Animal {
    public name: string;      // Accessible anywhere
    private age: number;      // Only inside Animal
    protected type: string;   // Animal and subclasses

    constructor(name: string, age: number, type: string) {
        this.name = name;
        this.age = age;
        this.type = type;
    }

    public getName() {
        return this.name;
    }

    private getAge() {
        return this.age;
    }
}

class Dog extends Animal {
    constructor(name: string, age: number) {
        super(name, age, "Dog");
    }

    public describeDog(): string {
        // Can use this.type (protected), not this.age (private)
        return `${this.name} is a ${this.type}`;
    }
}

const myDog = new Dog("Buster", 5);
console.log(myDog.name);          // Accessible (public)
// console.log(myDog.age);       // Error! age is private
// console.log(myDog.type);      // Error! type is protected
console.log(myDog.describeDog()); // Buster is a Dog
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Use private for sensitive data.
  • Use protected if subclasses need access.
  • Use public for properties/methods that can be exposed.

Remember: Clearly marking your class fields helps enforce intended usage and prevents bugs!

Top comments (0)