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
Access Modifiers in TypeScript
In TypeScript, access modifiers control the visibility and accessibility of class members, such as properties and methods, aligning with the principles of encapsulation and information hiding in object-oriented programming. Public: Members are accessible from anywhere; this is the default modifier i
4 min read
TypeScript Object Type readonly Properties
In TypeScript, the readonly modifier ensures that a property can be assigned a value only once during initialization and cannot be changed thereafter. This immutability helps prevent accidental modifications to object properties, enhancing code reliability.You can apply readonly to properties in cla
3 min read
How to Access TypeScript Private Members ?
In this TypeScript article, we will learn how to access the TypeScript private members using different approaches. We can interact with the encapsulated components within the class and access them in the application. There are three different approaches through which we can access TypeScript private
3 min read
TypeScript Object Type Property Modifiers
TypeScript Type Property Modifiers are used to specify each property in an object such as: the type, whether the property is optional, and whether the property can be written to. TypeScript Object Type Property Modifiers:readonly Properties: An object type with readonly properties specifies that the
3 min read
Difference Between Const and Readonly in TypeScript
The const and readonly both are used to create the variables and properties that can not be re-assigned once they get initialized by some value. But they are different from each other. Let us discuss the differences between them. ConstThe const keyword is used to declare the constant variables that
4 min read
How to make object properties immutable in TypeScript ?
In this article, we will try to understand how we could make object properties immutable in TypeScript. JavaScript is a highly dynamic and flexible language, hence making object properties in JavaScript immutable is a little bit typical (although we may implement it somehow using a const data type t
2 min read
TypeScript Indexed Access Types
TypeScript's Indexed Access Types allow you to access the type of a specific property within an object or array using bracket notation (Type[Key]). This feature provides precise type information about properties or elements, enhancing type safety when accessing deeply nested structures or specific o
3 min read
How to Create Deep Readonly Type in Typescript?
In TypeScript, the readonly access modifier is a powerful tool that ensures immutability by marking properties of a class as immutable. Once a property is markedreadonly, it cannot be reassigned. This is highly useful for maintaining consistent and safe data structures, especially in scenarios such
3 min read
TypeScript Optional Properties Type
TypeScript Opional properties type provides a way of defining the parts that are not necessarily required. TypeScript Optional Properties TypesOptional Properties are properties that are not required mandatorily and can be omitted when not needed.In TypeScript, you can define optional properties in
6 min read
How do I dynamically assign properties to an object in TypeScript?
In TypeScript, we can not assign the properties dynamically to an object directly by using the dot operator and the square brackets syntax which we generally use to assign dynamic properties in Vanilla JavaScript. JavaScript is a dynamically typed language and the type of a variable is determined at
3 min read