TypeScript - Access Modifiers and Readonly Properties
Last Updated :
11 Feb, 2025
In TypeScript, access modifiers and readonly properties help define how class members (properties and methods) can be accessed and modified. Access modifiers control the visibility of a class member, determining where it can be accessed from. Readonly properties, on the other hand, ensure that a variable can only be assigned a value once.
Access Modifiers
Access modifiers in TypeScript are used to set the visibility of properties and methods. They provide a way to control the accessibility of members, offering a higher degree of encapsulation. They allow developers to enforce better encapsulation and control over how class members are accessed so that the internal workings of a class are protected from outside interference.
Types of Access Modifiers
1. public: The member is accessible anywhere. It can be accessed inside the class, outside the class, and in derived classes.
JavaScript
class Car {
public make: string;
constructor(make: string) {
this.make = make;
}
}
const car = new Car("Toyota");
console.log(car.make);
Output
Toyota
In this code
- Class Declaration: A class Car is defined with a public property make of type string.
- Constructor: The constructor takes a make parameter and initializes the make property of the class.
- Creating an Instance: A new Car object is created with "Toyota" as the make.
- Accessing the Property: The make property of the car instance is logged to the console.
2. private: The private access modifier restricts access to the member, making it inaccessible outside the class, even by instances of derived classes, ensuring that the member is used only within the class where it is defined.
JavaScript
class Car {
private make: string;
constructor(make: string) {
this.make = make;
}
public getMake(): string {
return this.make;
}
}
const car = new Car("Toyota");
console.log(car.getMake());
Output
Toyota
In this code
- Class Declaration: A class Car is defined with a private property make of type string.
- Constructor: The constructor takes a make parameter and assigns it to the private make property.
- Private Member: The make property is private, meaning it cannot be accessed directly from outside the class.
- Public Method: A public method getMake() is defined to access the private make property and return its value.
- Creating an Instance: A new Car object is created with "Toyota" as the make.
- Accessing the Property: The getMake() method is called to access the make property, and its value is logged to the console.
3. protected: The protected access modifier allows a member to be accessed within the class and its derived subclasses, but it remains inaccessible outside the class hierarchy, providing more controlled access than public.
JavaScript
class Car {
protected make: string;
constructor(make: string) {
this.make = make;
}
}
class SportsCar extends Car {
public displayMake() {
console.log(this.make);
}
}
const car = new SportsCar("Ferrari");
car.displayMake();
Output
Ferrari
In this code
- The Car class has a protected property make, which is accessible within the class and its subclasses.
- The SportsCar class extends Car and has a method displayMake() that accesses the make property from the parent class.
- A SportsCar object is created with "Ferrari" as the make, and displayMake() is called to log the make.
For more detail read article- Access Modifiers in TypeScript
Readonly Properties
Readonly properties in TypeScript allow you to set the value only once, either during the initialization or in the constructor. After the initial assignment, the value cannot be changed.
JavaScript
class Car {
public readonly make: string;
constructor(make: string) {
this.make = make;
}
}
const car = new Car("Toyota");
console.log(car.make);
Output
Toyota
In this example
- The make property is declared as readonly, meaning it can be assigned a value only once, either during initialization or within the constructor.
- After the car object is created with the value "Toyota", trying to assign a new value to make results in an error, as it’s a readonly property.
Why Use Readonly Properties?
Readonly properties provide the following benefits:
- Immutability: Ensures that the property value cannot be altered after initialization, which is useful for creating objects with fixed, unchanging data.
- Data Integrity: Reduces the risk of accidental changes to important object properties.
- Code Predictability: Ensures that once a property is set, its value remains consistent throughout the lifetime of the object.
Readonly Arrays
You can also create readonly arrays in TypeScript by using the readonly modifier with array types.
JavaScript
class Book {
public readonly pages: readonly number[];
constructor(pages: number[]) {
this.pages = pages;
}
}
const book = new Book([100, 200, 300]);
console.log(book.pages);
In this example
- The pages property is a readonly array. It can only be assigned a value once (in the constructor).
- Attempts to modify the array (like using push) will result in an error, as the array is immutable.
Comparison: Readonly vs Const
While both readonly and const enforce immutability, they are used in different contexts:
- readonly is used for properties inside classes or interfaces, where the immutability applies to the property itself.
- const is used for variables, ensuring that the variable reference cannot be reassigned (but the value it points to can be mutable if it’s an object).
JavaScript
const car = { make: "Toyota" };
class Vehicle {
public readonly make: string;
constructor(make: string) {
this.make = make;
}
}
const vehicle = new Vehicle("BMW");
vehicle.make = "Audi";
In this code
- car is an object with a make property set to "Toyota".
- The Vehicle class has a readonly property make, which is set during construction and cannot be modified afterward.
- When trying to set vehicle.make = "Audi", TypeScript will throw an error because make is a readonly property and cannot be reassigned after initialization.
Comparison: Access Modifiers vs Readonly Properties
Feature | Access Modifiers | Readonly Properties |
---|
Purpose | Control visibility of members | Ensure the value of a property remains constant |
Applicability | Applied to methods, fields, classes | Applied to properties |
Modifications | Can be modified based on the modifier | Can only be set once, in constructor or declaration |
Usage of Readonly Properties
- Immutable Object Properties: Prevents changes to properties after object initialization.
- Class Design: Used in class properties that should remain constant after being set in the constructor.
- Readonly Arrays: Ensures arrays remain unchanged, preventing methods like push() or pop().
- Type Safety: Enforces immutability, reducing unintended modifications in the code.
- Interfaces & Types: Defines immutable properties in interfaces and type definitions.
For more detail read article- TypeScript Object Type readonly Properties
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read