0
0
Typescriptprogramming~5 mins

Read-only arrays in Typescript

Choose your learning style9 modes available
Introduction

Read-only arrays help you keep data safe by preventing changes after creation. This stops mistakes where data is changed by accident.

When you want to share a list of items but don't want anyone to change it.
When you pass an array to a function and want to make sure the function does not modify it.
When you have a fixed list of values that should stay the same throughout the program.
When you want to avoid bugs caused by accidental changes to arrays.
When you want to clearly show that an array is meant to be read-only in your code.
Syntax
Typescript
class ReadOnlyArrayExample {
  readonly numbers: readonly number[];

  constructor(numbers: readonly number[]) {
    this.numbers = numbers;
  }

  printNumbers(): void {
    for (const number of this.numbers) {
      console.log(number);
    }
  }
}

// Usage example
const example = new ReadOnlyArrayExample([1, 2, 3]);
example.printNumbers();

The readonly keyword before the array type means the array cannot be changed.

Using readonly before the property name means the property itself cannot be reassigned.

Examples
This shows a read-only array of numbers. Trying to add a number causes an error.
Typescript
const readOnlyNumbers: readonly number[] = [10, 20, 30];
// readOnlyNumbers.push(40); // Error: Property 'push' does not exist on type 'readonly number[]'.
The function accepts a read-only array, so it cannot change the array inside.
Typescript
function printNames(names: readonly string[]) {
  for (const name of names) {
    console.log(name);
  }
}

const myNames = ['Alice', 'Bob'];
printNames(myNames);
You cannot change elements by index in a read-only array.
Typescript
let letters: readonly string[] = ['a', 'b', 'c'];
// letters[0] = 'z'; // Error: Index signature in type 'readonly string[]' only permits reading.
Read-only arrays can be empty and still work normally for reading.
Typescript
const emptyReadOnlyArray: readonly number[] = [];
console.log(emptyReadOnlyArray.length); // 0
Sample Program

This program creates a class holding a read-only array of strings. It prints all items. Attempts to change the array cause errors, showing the array is protected.

Typescript
class ReadOnlyArrayDemo {
  readonly items: readonly string[];

  constructor(items: readonly string[]) {
    this.items = items;
  }

  printItems(): void {
    console.log('Items in the array:');
    for (const item of this.items) {
      console.log(item);
    }
  }
}

const fruits: readonly string[] = ['apple', 'banana', 'cherry'];
const demo = new ReadOnlyArrayDemo(fruits);
demo.printItems();

// Trying to modify the array will cause errors
// demo.items.push('date'); // Error
// demo.items[0] = 'apricot'; // Error

console.log('Length of array:', demo.items.length);
OutputSuccess
Important Notes

Time complexity for reading elements is O(1), same as normal arrays.

Space complexity is the same as a normal array since it just prevents changes, not copies.

Common mistake: Trying to use methods like push or assigning to indexes causes errors because the array is read-only.

Use read-only arrays when you want to protect data from accidental changes but still allow reading and looping.

Summary

Read-only arrays prevent changes to the array and its elements.

They help keep data safe and avoid bugs from accidental modifications.

Use readonly keyword before the array type to make it read-only.