readonly modifier in Typescript

In TypeScript, the readonly modifier is used to make a property immutable, meaning that once it is assigned a value, it cannot be changed. This is particularly useful for defining constants or values that should not be modified after their initial assignment.

Using readonly with Properties

Here’s an example to illustrate the usage of the readonly modifier:


class Person {
    // Readonly properties
    readonly name: string;
    readonly age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age= age;
    }

    // Method to display person details
    displayDetails(): void {
        console.log(`Name: ${this.name}, Age: ${this.age}`);
    }
}

const person = new Person("John", 40);
console.log(person.name); // John
console.log(person.age); // 40

// Trying to modify readonly properties (will cause an error)
// person.name = "Tom"; // Error: Cannot assign to 'name' because it is a read-only property.
// person.age= 38; // Error: Cannot assign to 'age' because it is a read-only property.

In this example, the properties name and age are marked as readonly, which means their values can only be set when the object is created (in the constructor) and cannot be changed afterwards.

Using readonly with Arrays and Tuples

The readonly modifier can also be used with arrays and tuples to make them immutable:


// Readonly array
const readonlyArray: readonly number[] = [1, 2, 3];
// readonlyArray[0] = 10; // Error: Index signature in type 'readonly number[]' only permits reading.
// readonlyArray.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.

// Readonly tuple
let readonlyTuple: readonly [number, string] = [1, "hello"];
// readonlyTuple[0] = 10; // Error: Index signature in type 'readonly [number, string]' only permits reading.

Using readonly with Interfaces and Type Aliases

You can also define readonly properties in interfaces and type aliases:


interface Person {
    readonly name: string;
    readonly age: number;
}

const person: Person = { name: "John", age: 40};
// person.name = "Tom"; // Error: Cannot assign to 'name' because it is a read-only property.

type Point = {
    readonly x: number;
    readonly y: number;
};

const point: Point = { x: 10, y: 20 };
// point.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.

Summary

  • readonly modifier: Used to make properties immutable.
  • Usage: Can be applied to properties, arrays, tuples, interfaces, and type aliases.
  • Effect: Once a readonly property is assigned a value, it cannot be changed.

The readonly modifier is a powerful feature in TypeScript that helps enforce immutability and ensures that certain values remain constant throughout the lifecycle of an object.