Introduction
In this chapter, we will explore access modifiers in TypeScript. Access modifiers control the visibility of class members (properties and methods). Understanding how to use access modifiers is essential for encapsulating data and providing controlled access to class members in TypeScript programs.
Table of Contents
- Definition
- Public Access Modifier
- Private Access Modifier
- Protected Access Modifier
- Readonly Modifier
- Access Modifiers in Constructors
- Complete Example with Output
- Conclusion
Definition
Access modifiers in TypeScript define the visibility and accessibility of class members. The three main access modifiers are public
, private
, and protected
. Additionally, TypeScript provides the readonly
modifier to make properties immutable after initialization.
Public Access Modifier
Definition
The public
modifier allows class members to be accessible from anywhere. By default, all class members are public
if no access modifier is specified.
Example
This example demonstrates the use of the public
access modifier.
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public greet(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
let person = new Person("Ramesh", 25);
console.log(person.greet()); // Output: Hello, my name is Ramesh and I am 25 years old.
Output
Hello, my name is Ramesh and I am 25 years old.
Private Access Modifier
Definition
The private
modifier restricts access to class members, making them accessible only within the class they are defined.
Example
This example demonstrates the use of the private
access modifier.
class Employee {
public name: string;
private salary: number;
constructor(name: string, salary: number) {
this.name = name;
this.salary = salary;
}
public getSalary(): number {
return this.salary;
}
private calculateBonus(): number {
return this.salary * 0.1;
}
}
let employee = new Employee("Suresh", 50000);
console.log(employee.name); // Output: Suresh
console.log(employee.getSalary()); // Output: 50000
// console.log(employee.calculateBonus()); // Error: Property 'calculateBonus' is private and only accessible within class 'Employee'.
Output
Suresh
50000
Protected Access Modifier
Definition
The protected
modifier allows access to class members within the class and its subclasses.
Example
This example demonstrates the use of the protected
access modifier.
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected makeSound(): string {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
public bark(): string {
return `${this.name} barks.`;
}
}
let dog = new Dog("Tommy");
console.log(dog.bark()); // Output: Tommy barks.
// console.log(dog.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
Output
Tommy barks.
Readonly Modifier
Definition
The readonly
modifier makes a property immutable after it is initialized. It can be used with any access modifier.
Example
This example demonstrates the use of the readonly
modifier.
class Book {
public readonly title: string;
public readonly author: string;
constructor(title: string, author: string) {
this.title = title;
this.author = author;
}
public getSummary(): string {
return `${this.title} is written by ${this.author}.`;
}
}
let book = new Book("TypeScript Basics", "John Doe");
console.log(book.getSummary()); // Output: TypeScript Basics is written by John Doe.
// book.title = "Advanced TypeScript"; // Error: Cannot assign to 'title' because it is a read-only property.
Output
TypeScript Basics is written by John Doe.
Access Modifiers in Constructors
Access modifiers can be used directly in constructor parameters to automatically create and initialize class properties.
Example
This example demonstrates the use of access modifiers in constructor parameters.
class Car {
constructor(public model: string, private year: number) {}
public display(): string {
return `This car is a ${this.model} from ${this.year}.`;
}
}
let car = new Car("Toyota", 2020);
console.log(car.display()); // Output: This car is a Toyota from 2020.
console.log(car.model); // Output: Toyota
// console.log(car.year); // Error: Property 'year' is private and only accessible within class 'Car'.
Output
This car is a Toyota from 2020.
Toyota
Complete Example with Output
In this section, we will combine the examples into a single TypeScript file, compile it to JavaScript, and run it to see the output.
TypeScript Code
You can test the following code in the TypeScript Playground:
// Public Access Modifier
class Person {
public name: string;
public age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public greet(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
let person = new Person("Ramesh", 25);
console.log(person.greet()); // Output: Hello, my name is Ramesh and I am 25 years old.
// Private Access Modifier
class Employee {
public name: string;
private salary: number;
constructor(name: string, salary: number) {
this.name = name;
this.salary = salary;
}
public getSalary(): number {
return this.salary;
}
private calculateBonus(): number {
return this.salary * 0.1;
}
}
let employee = new Employee("Suresh", 50000);
console.log(employee.name); // Output: Suresh
console.log(employee.getSalary()); // Output: 50000
// console.log(employee.calculateBonus()); // Error: Property 'calculateBonus' is private and only accessible within class 'Employee'.
// Protected Access Modifier
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
protected makeSound(): string {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
public bark(): string {
return `${this.name} barks.`;
}
}
let dog = new Dog("Tommy");
console.log(dog.bark()); // Output: Tommy barks.
// console.log(dog.name); // Error: Property 'name' is protected and only accessible within class 'Animal' and its subclasses.
// Readonly Modifier
class Book {
public readonly title: string;
public readonly author: string;
constructor(title: string, author: string) {
this.title = title;
this.author = author;
}
public getSummary(): string {
return `${this.title} is written by ${this.author}.`;
}
}
let book = new Book("TypeScript Basics", "John Doe");
console.log(book.getSummary()); // Output: TypeScript Basics is written by John Doe.
// book.title = "Advanced TypeScript"; // Error: Cannot assign to 'title' because it is a read-only property.
// Access Modifiers in Constructors
class Car {
constructor(public model: string, private year: number) {}
public display(): string {
return `This car is a ${this.model} from ${this.year}.`;
}
}
let car = new Car("Toyota", 2020);
console.log(car.display()); // Output: This car is a Toyota from 2020.
console.log(car.model); // Output: Toyota
// console.log(car.year); // Error: Property 'year' is private and only accessible within class 'Car'.
Conclusion
In this chapter, we covered access modifiers in TypeScript, including the public
, private
, and protected
modifiers, as well as the readonly
modifier. We also discussed how to use access modifiers in constructors. We provided a complete example with its output to illustrate how these concepts work in TypeScript. Understanding access modifiers is essential for encapsulating data and providing controlled access to class members in TypeScript programs.
Comments
Post a Comment
Leave Comment