Read-only arrays help you keep data safe by preventing changes after creation. This stops mistakes where data is changed by accident.
Read-only arrays in 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.
const readOnlyNumbers: readonly number[] = [10, 20, 30]; // readOnlyNumbers.push(40); // Error: Property 'push' does not exist on type 'readonly number[]'.
function printNames(names: readonly string[]) { for (const name of names) { console.log(name); } } const myNames = ['Alice', 'Bob']; printNames(myNames);
let letters: readonly string[] = ['a', 'b', 'c']; // letters[0] = 'z'; // Error: Index signature in type 'readonly string[]' only permits reading.
const emptyReadOnlyArray: readonly number[] = []; console.log(emptyReadOnlyArray.length); // 0
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.
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);
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.
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.