ProgrammingFrontend Developer

What is the keyword 'readonly' in TypeScript? How and when should it be used? What are its features compared to const?

Pass interviews with Hintsage AI assistant

Answer.

The keyword readonly in TypeScript is used for properties of objects and arrays to prevent them from being modified after initialization:

  • It is used in the description of interfaces, types, and classes to ensure that the value of a field cannot be changed after it has been set.
  • readonly applies only to object properties and not to variables.
  • Unlike const, which indicates that a variable cannot be reassigned but does not prevent modification of the object's content, readonly specifically prevents modification of the field or array element itself.

Example:

interface User { readonly id: number; name: string; } const user: User = { id: 1, name: 'Anna' }; user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.

For arrays:

const nums: readonly number[] = [1, 2, 3]; nums.push(4); // Error: Property 'push' does not exist on type 'readonly number[]'.

Trick question.

What is the difference between const and readonly in TypeScript? Can they replace each other?

Answer: No, they cannot. const is a restriction on the variable itself (it cannot be reassigned), while readonly is a restriction on individual object properties or array elements, but the variable itself can still be modified (if allowed by context).

Example:

const arr: readonly number[] = [1, 2, 3]; // arr = [2, 3, 4]; // Error due to const // arr[0] = 5; // Error due to readonly

Story

On a project for a financial platform, regular arrays number[] were used instead of readonly number[] when working with user data. As a result, one function accidentally modified the input data — the amounts in the arrays were used in different places, leading to discrepancies in reports. The error was discovered several days later, costing the company time on auditing and data restoration.


Story

On the internal API, const and readonly were mixed up, mistakenly believing that const user: User would prevent field changes. As a result, it became possible to change the object's fields, even though this was unacceptable according to the specifications. Due to ignorance of the difference, there were leaks of sensitive data between services.


Story

In an open source library, one data structure was accidentally made mutable because readonly was forgotten in the interface definition. This allowed third-party developers to modify private data at runtime, causing bugs that required refactoring to fix.