Bird
Raised Fist0
Typescriptprogramming~10 mins

Read-only arrays in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Read-only arrays
Declare array with readonly type
↓
Try to read elements
→Allowed
↓
Try to modify elements
→Compile error: modification not allowed
↓
Use array safely without changes
↓
End
You create an array that cannot be changed. Reading is allowed, but any change causes an error.
Execution Sample
Typescript
const nums: readonly number[] = [1, 2, 3];
console.log(nums[0]);
// nums[1] = 5; // Error: cannot assign to readonly array
const newNums = nums.map(x => x * 2);
console.log(newNums);
This code shows a readonly array, reading elements, and creating a new array by mapping.
Execution Table
StepActionCode LineResultNotes
1Declare readonly array numsconst nums: readonly number[] = [1, 2, 3];nums = [1, 2, 3]Array created, cannot be changed
2Read first elementconsole.log(nums[0]);Output: 1Reading allowed
3Attempt to modify element// nums[1] = 5;Compile errorModification not allowed on readonly array
4Create new array by mapconst newNums = nums.map(x => x * 2);newNums = [2, 4, 6]map returns new array, original unchanged
5Print newNumsconsole.log(newNums);Output: [2, 4, 6]Shows doubled values
💡 Execution stops because modification line is commented out due to compile error
Variable Tracker
VariableStartAfter Step 1After Step 4Final
numsundefined[1, 2, 3][1, 2, 3][1, 2, 3]
newNumsundefinedundefined[2, 4, 6][2, 4, 6]
Key Moments - 3 Insights
Why can't we assign a new value to nums[1]?
Because nums is declared as a readonly array, any attempt to change its elements causes a compile error, as shown in step 3 of the execution table.
Can we read elements from a readonly array?
Yes, reading elements is allowed and safe, as shown in step 2 where nums[0] is read and printed.
How can we create a changed version of a readonly array?
By using methods like map that return a new array without modifying the original, as shown in step 4 where newNums is created.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of nums after step 4?
A[2, 4, 6]
Bundefined
C[1, 2, 3]
DCompile error
💡 Hint
Check the variable_tracker row for nums after step 4
At which step does the code try to modify the readonly array?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the 'Action' column in the execution_table for modification attempts
If we remove the comment from the modification line, what happens?
AThe array nums changes to [1, 5, 3]
BA compile error occurs
CThe program prints 5
DThe map function fails
💡 Hint
Refer to the 'Result' column in step 3 of the execution_table
Concept Snapshot
Readonly arrays in TypeScript:
- Declared with 'readonly' keyword
- Elements can be read but not changed
- Any modification causes compile error
- Methods like map return new arrays
- Useful for safe, immutable data
Full Transcript
This visual trace shows how readonly arrays work in TypeScript. First, we declare an array with the readonly keyword, which means we can read elements but cannot change them. Reading nums[0] prints 1 successfully. Trying to assign a new value to nums[1] causes a compile error, so that line is commented out. We then use the map method to create a new array with doubled values, which is allowed because it does not change the original array. The new array is printed as [2, 4, 6]. The variable tracker confirms nums stays unchanged throughout. Key moments clarify why modification is disallowed and how to work with readonly arrays safely. The quiz tests understanding of these steps.

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