WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Intermediate · question 28 of 100

What is the purpose of the ’readonly’ modifier in TypeScript?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

In TypeScript, the ‘readonly‘ modifier is used to mark a property or an index signature declaration as read-only. Once a property is marked as ‘readonly‘, its value cannot be changed after it has been initialized.

There are several reasons why you’d want to use ‘readonly‘ in your code:

1. *Immutability*: The ‘readonly‘ modifier ensures that the value of a property is not modified after initialization. This can help enforce immutability or protect certain properties from being altered.

2. *Error prevention*: Using ‘readonly‘ helps prevent accidental changes to the value of a property, which could lead to bugs or unexpected behavior in your program.

3. *Code clarity*: When a property is marked as ‘readonly‘, it communicates to other developers that the value should not be changed after initialization, making your code more clear and understandable.

Here’s an example of how to use the ‘readonly‘ modifier in TypeScript:

class Circle {
    readonly pi: number; // Read-only property
    readonly radius: number;

    constructor(radius: number) {
        this.pi = 3.14159265359;
        this.radius = radius;
    }

    area(): number {
        return this.pi * this.radius * this.radius;
    }
}

let circle = new Circle(5);
circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property

Here, the properties ‘pi‘ and ‘radius‘ are marked as ‘readonly‘, indicating that their values should not be changed after they are initialized in the constructor.

For an array, you can use the ‘ReadonlyArray‘ or ‘Readonly<T>‘type to create a read-only array:

let numbers: ReadonlyArray<number> = [1, 2, 3, 4, 5];
numbers.push(6); // Error: Property 'push' does not exist on type 'ReadonlyArray<number>'

let moreNumbers: Readonly<number[]> = [1, 2, 3, 4, 5];
moreNumbers[0] = 0; // Error: Index signature in type 'Readonly<number[]>' only permits reading

In conclusion, the ‘readonly‘ modifier in TypeScript is a useful tool for ensuring immutability and preventing accidental changes to variables or properties in your code, leading to more robust and clear code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics