Skip to main content

Access Modifiers in TypeScript (Live Playground)

In this tutorial, we will explore access modifiers in TypeScript, which are essential for controlling the visibility and accessibility of class members in advanced object-oriented programming (OOP).

Public Access Modifier

By default, all class members in TypeScript are public. Public members can be accessed from any part of the code.

TypeScript
class Animal {
public name: string;

constructor(name: string) {
this.name = name;
}

public speak(): void {
console.log(`${this.name} makes a sound.`);
}
}

const animal = new Animal('Dog');
animal.speak(); // Dog makes a sound.
Live Playground, Try it Yourself

Private Access Modifier

The private access modifier restricts the visibility of class members to the class they are declared in. Private members cannot be accessed from outside the class.

TypeScript
class Animal {
private name: string;

constructor(name: string) {
this.name = name;
}

speak(): void {
console.log(`${this.name} makes a sound.`);
}
}

const animal = new Animal('Dog');
animal.speak(); // Dog makes a sound.
console.log(animal.name); // Error: Property 'name' is private and only accessible within class 'Animal'.
Live Playground, Try it Yourself

Protected Access Modifier

The protected access modifier is similar to private, but protected members can also be accessed from subclasses.

TypeScript
class Animal {
protected name: string;

constructor(name: string) {
this.name = name;
}
}

class Dog extends Animal {
speak(): void {
console.log(`${this.name} barks.`);
}
}

const dog = new Dog('Max');
dog.speak(); // Max barks.
console.log(dog.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
Live Playground, Try it Yourself

Readonly Access Modifier

The readonly modifier can be used to mark a class member as read-only. Readonly members can only be initialized at the time of declaration or within the constructor.

TypeScript
class Animal {
readonly name: string;

constructor(name: string) {
this.name = name;
}
}

const animal = new Animal('Dog');
console.log(animal.name); // Dog
animal.name = 'Cat'; // Error: Cannot assign to 'name' because it is a read-only property.
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have explored access modifiers in TypeScript, which are essential for controlling the visibility and accessibility of class members in advanced object-oriented programming (OOP). As you continue learning TypeScript, make sure to practice using access modifiers and other OOP techniques to create more secure, maintainable, and organized code in your applications.