Open In App

TypeScript - Access Modifiers and Readonly Properties

Last Updated : 11 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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


Next Article

Similar Reads