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.
Practice
readonly array in TypeScript do?Solution
Step 1: Understand the
Thereadonlykeywordreadonlykeyword before an array type means the array cannot be changed after it is created.Step 2: Effects on the array
This means you cannot add, remove, or modify elements in the array once it is set.Final Answer:
Prevents any changes to the array elements after creation -> Option DQuick Check:
readonlyarrays are immutable [OK]
- Thinking readonly only blocks length changes
- Assuming elements can be modified individually
- Confusing readonly with optional elements
Solution
Step 1: Recall the correct
In TypeScript,readonlysyntaxreadonlycomes before the array type, likereadonly number[].Step 2: Check each option
let nums: readonly number[] = [1, 2, 3]; usesreadonly number[], which is correct syntax. Others placereadonlyincorrectly.Final Answer:
let nums: readonly number[] = [1, 2, 3]; -> Option AQuick Check:
readonlybefore type [OK]
- Placing readonly after the array brackets
- Using readonly as a variable modifier
- Trying to put readonly inside the array literal
const arr: readonly string[] = ['a', 'b', 'c'];
// arr.push('d');
console.log(arr.length);Solution
Step 1: Understand the array declaration
The arrayarris declared asreadonly string[]with 3 elements: 'a', 'b', 'c'.Step 2: Check the commented out push and output
Thepushline is commented out, so it does not run. The length remains 3.Final Answer:
3 -> Option CQuick Check:
Readonly array length unchanged = 3 [OK]
- Assuming push works on readonly arrays
- Expecting length to increase despite push commented
- Confusing runtime errors with compile-time errors
const nums: readonly number[] = [1, 2, 3]; nums[0] = 10;
Solution
Step 1: Understand the readonly array behavior
The arraynumsis readonly, so its elements cannot be changed after creation.Step 2: Analyze the assignment to an element
Trying to assignnums[0] = 10causes an error because elements are read-only.Final Answer:
Cannot assign to '0' because it is a read-only property -> Option BQuick Check:
Readonly elements cannot be changed [OK]
- Thinking only array structure is readonly, not elements
- Ignoring TypeScript error messages
- Assuming semicolon missing causes error
function process(items: readonly number[]) {
// Which line is valid?
// A) items.push(5);
// B) items[0] = 10;
// C) const first = items[0];
// D) items.length = 0;
}Solution
Step 1: Understand read-only array restrictions
Read-only arrays do not allow modifying methods likepush, element assignment, or length changes.Step 2: Check each operation
Only reading elements, likeconst first = items[0];, is allowed. Others cause errors.Final Answer:
const first = items[0]; -> Option AQuick Check:
Reading elements allowed, modifying disallowed [OK]
- Trying to push or assign elements in readonly arrays
- Attempting to change array length
- Confusing read-only with mutable arrays
Ready to prove it?
Pass the test and this pattern moves unknown
