In TypeScript, access modifiers are keywords that control the visibility of class members (properties and methods). They help in encapsulating data and ensuring that class members can only be accessed or modified under controlled conditions. This tutorial will cover three main access modifiers: public, private, and protected.
Let's explore each access modifier with practical examples.
By default, all members of a class are public. This means they can be accessed from anywhere.
1class Animal {2name: string;34constructor(name: string) {5this.name = name;6}78greet() {9console.log(`Hello, my name is ${this.name}.`);10}11}1213const dog = new Animal('Buddy');14dog.greet(); // Output: Hello, my name is Buddy.15console.log(dog.name); // Output: Buddy
Private members can only be accessed within the class that defines them. They are not accessible from outside the class.
1class Animal {2private name: string;34constructor(name: string) {5this.name = name;6}78greet() {9console.log(`Hello, my name is ${this.name}.`);10}11}1213const dog = new Animal('Buddy');14dog.greet(); // Output: Hello, my name is Buddy.15// console.log(dog.name); // Error: Property 'name' is private and only accessible within class 'Animal'.
Protected members are similar to private members but can also be accessed by subclasses.
1class Animal {2protected name: string;34constructor(name: string) {5this.name = name;6}78greet() {9console.log(`Hello, my name is ${this.name}.`);10}11}1213class Dog extends Animal {14breed: string;1516constructor(name: string, breed: string) {17super(name);18this.breed = breed;19}2021displayInfo() {22console.log(`This dog's name is ${this.name} and it is a ${this.breed}.`);23}24}2526const myDog = new Dog('Buddy', 'Golden Retriever');27myDog.displayInfo(); // Output: This dog's name is Buddy and it is a Golden Retriever.28// console.log(myDog.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
Inheritance in TypeScript
Understanding access modifiers is crucial for building robust and maintainable applications. In the next section, we will explore how inheritance works in TypeScript, including how access modifiers behave in subclass scenarios.
Info
Access modifiers help in encapsulating data and controlling the visibility of class members, which is essential for maintaining clean and secure code.