Bird
Raised Fist0
Typescriptprogramming~5 mins

Read-only arrays in Typescript

Choose your learning style10 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.

Practice

(1/5)
1. What does a readonly array in TypeScript do?
easy
A. Only prevents changing the array length
B. Allows adding new elements but not removing existing ones
C. Makes the array elements optional
D. Prevents any changes to the array elements after creation

Solution

  1. Step 1: Understand the readonly keyword

    The readonly keyword before an array type means the array cannot be changed after it is created.
  2. Step 2: Effects on the array

    This means you cannot add, remove, or modify elements in the array once it is set.
  3. Final Answer:

    Prevents any changes to the array elements after creation -> Option D
  4. Quick Check:

    readonly arrays are immutable [OK]
Hint: Readonly arrays block all changes to elements [OK]
Common Mistakes:
  • Thinking readonly only blocks length changes
  • Assuming elements can be modified individually
  • Confusing readonly with optional elements
2. Which of the following is the correct syntax to declare a read-only array of numbers in TypeScript?
easy
A. let nums: readonly number[] = [1, 2, 3];
B. let nums: number[] readonly = [1, 2, 3];
C. let nums: number readonly[] = [1, 2, 3];
D. let nums: number[] = readonly [1, 2, 3];

Solution

  1. Step 1: Recall the correct readonly syntax

    In TypeScript, readonly comes before the array type, like readonly number[].
  2. Step 2: Check each option

    let nums: readonly number[] = [1, 2, 3]; uses readonly number[], which is correct syntax. Others place readonly incorrectly.
  3. Final Answer:

    let nums: readonly number[] = [1, 2, 3]; -> Option A
  4. Quick Check:

    readonly before type [OK]
Hint: Put readonly before the array type, not after [OK]
Common Mistakes:
  • Placing readonly after the array brackets
  • Using readonly as a variable modifier
  • Trying to put readonly inside the array literal
3. What will be the output of this TypeScript code?
const arr: readonly string[] = ['a', 'b', 'c'];
// arr.push('d');
console.log(arr.length);
medium
A. 4
B. undefined
C. 3
D. Error: Property 'push' does not exist on type 'readonly string[]'

Solution

  1. Step 1: Understand the array declaration

    The array arr is declared as readonly string[] with 3 elements: 'a', 'b', 'c'.
  2. Step 2: Check the commented out push and output

    The push line is commented out, so it does not run. The length remains 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    Readonly array length unchanged = 3 [OK]
Hint: Commented push means length stays same [OK]
Common Mistakes:
  • Assuming push works on readonly arrays
  • Expecting length to increase despite push commented
  • Confusing runtime errors with compile-time errors
4. Identify the error in this TypeScript code using a read-only array:
const nums: readonly number[] = [1, 2, 3];
nums[0] = 10;
medium
A. Type 'number' is not assignable to type 'readonly number[]'
B. Cannot assign to '0' because it is a read-only property
C. Syntax error: missing semicolon
D. No error, code runs fine

Solution

  1. Step 1: Understand the readonly array behavior

    The array nums is readonly, so its elements cannot be changed after creation.
  2. Step 2: Analyze the assignment to an element

    Trying to assign nums[0] = 10 causes an error because elements are read-only.
  3. Final Answer:

    Cannot assign to '0' because it is a read-only property -> Option B
  4. Quick Check:

    Readonly elements cannot be changed [OK]
Hint: Readonly arrays block element assignment [OK]
Common Mistakes:
  • Thinking only array structure is readonly, not elements
  • Ignoring TypeScript error messages
  • Assuming semicolon missing causes error
5. Given a function that accepts a read-only array, which of these operations inside the function is allowed?
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;
}
hard
A. const first = items[0];
B. items.push(5);
C. items[0] = 10;
D. items.length = 0;

Solution

  1. Step 1: Understand read-only array restrictions

    Read-only arrays do not allow modifying methods like push, element assignment, or length changes.
  2. Step 2: Check each operation

    Only reading elements, like const first = items[0];, is allowed. Others cause errors.
  3. Final Answer:

    const first = items[0]; -> Option A
  4. Quick Check:

    Reading elements allowed, modifying disallowed [OK]
Hint: Readonly arrays allow reading, not modifying [OK]
Common Mistakes:
  • Trying to push or assign elements in readonly arrays
  • Attempting to change array length
  • Confusing read-only with mutable arrays
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard