- TypeScript Tutorial
- TypeScript Home
- TypeScript Introduction
- TypeScript Setup
- TypeScript First Program
- TypeScript vs JavaScript
- TypeScript Data Types
- TypeScript Type Inference
- TypeScript Type Annotations
- TypeScript Interfaces
- TypeScript Enums
- TypeScript Type Aliases
- TypeScript Type Assertions
- TypeScript Variables
- TypeScript Functions
- TypeScript Functions
- TypeScript Optional Parameters
- TypeScript Default Parameters
- TypeScript Rest Parameters
- TypeScript Arrow Functions
- Classes and Objects
- Introduction to Classes
- Properties and Methods
- Access Modifiers
- Static Members
- Inheritance
- Abstract Classes
- Interfaces vs Classes
- Advanced Types
- TypeScript Union Types
- TypeScript Intersection Types
- TypeScript Literal Types
- TypeScript Nullable Types
- TypeScript Type Guards
- TypeScript Discriminated Unions
- TypeScript Index Signatures
- TypeScript Generics
- Introduction to Generics
- TypeScript Generic Functions
- TypeScript Generic Classes
- TypeScript Generic Constraints
- TypeScript Modules
- Introduction to Modules
- TypeScript Import and Export
- TypeScript Default Exports
- TypeScript Namespace
- Decorators
- Introduction to Decorators
- TypeScript Class Decorators
- TypeScript Method Decorators
- TypeScript Property Decorators
- TypeScript Parameter Decorators
- Configuration
- TypeScript tsconfig.json File
- TypeScript Compiler Options
- TypeScript Strict Mode
- TypeScript Watch Mode
Access Modifiers in TypeScript
Access modifiers in TypeScript allow you to control the visibility and accessibility of class members (properties and methods). By using access modifiers, you can encapsulate your data and control how it is accessed, ensuring better data security and design flexibility.
Key Access Modifiers:
- public
- private
- protected
public
The public access modifier is the default modifier in TypeScript. Members marked as public are accessible from anywhere, both inside and outside of the class.
Example:
class Car {
public make: string;
public model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
public displayInfo(): void {
console.log(`Make: ${this.make}, Model: ${this.model}`);
}
}
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.make); // Accessible outside the class
myCar.displayInfo(); // Accessible outside the class
In this example:
- Both
makeandmodelarepublic, meaning they can be accessed from outside theCarclass. - The method
displayInfo()is alsopublic, so it can be called from outside the class.
private
The private access modifier restricts access to the members of a class. A private member can only be accessed within the class itself and cannot be accessed outside of it.
Example:
class Employee {
private id: number;
private name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
private displayInfo(): void {
console.log(`ID: ${this.id}, Name: ${this.name}`);
}
public showDetails(): void {
this.displayInfo(); // Private method can be called inside the class
}
}
const emp = new Employee(1, "John");
// console.log(emp.id); // Error: Property 'id' is private and only accessible within class 'Employee'.
// emp.displayInfo(); // Error: Method 'displayInfo' is private and only accessible within class 'Employee'.
emp.showDetails(); // Valid: Can access private method within the class
In this example:
- The
idandnameproperties are marked asprivate, so they cannot be accessed directly from outside theEmployeeclass. - The
displayInfo()method is also private and can only be called within the class. - The
showDetails()method is public, so it can be called from outside the class to indirectly access private methods.
protected
The protected access modifier is similar to private, but it allows access within the class and its subclasses (derived classes). A protected member cannot be accessed outside of the class or its subclasses.
Example:
class Animal {
protected species: string;
constructor(species: string) {
this.species = species;
}
}
class Dog extends Animal {
public breed: string;
constructor(species: string, breed: string) {
super(species);
this.breed = breed;
}
public displayInfo(): void {
console.log(`Species: ${this.species}, Breed: ${this.breed}`);
}
}
const dog = new Dog("Canine", "Bulldog");
console.log(dog.breed); // Accessible from outside
// console.log(dog.species); // Error: Property 'species' is protected and only accessible within class 'Animal' and its subclasses.
dog.displayInfo(); // Valid: Can access protected property in subclass method
In this example:
- The
speciesproperty is marked asprotected, so it can be accessed by theDogsubclass but not from outside the class. - The
breedproperty ispublic, so it can be accessed from outside theDogclass.
Readonly
In addition to public, private, and protected, TypeScript also provides the readonly modifier, which ensures that a property can only be assigned a value once — either during initialization or in the constructor.
Example:
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
}
const circle = new Circle(5);
console.log(circle.radius); // Output: 5
// circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property.
In this example:
- The
radiusproperty is marked asreadonly, meaning it cannot be modified after the object is created.
Summary
Access modifiers (public, private, protected) in TypeScript are essential for controlling the visibility and accessibility of class members. By appropriately using these modifiers, you can encapsulate and protect your data, ensuring better control over how it is accessed and manipulated.
- public members are accessible from anywhere.
- private members are only accessible within the class.
- protected members are accessible within the class and its subclasses.
- The
readonlymodifier makes a property immutable after it is initialized.