0
0
Typescriptprogramming~20 mins

Read-only arrays in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Read-only Arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this TypeScript code using a readonly array?
Consider the following TypeScript code. What will be printed to the console?
Typescript
const nums: readonly number[] = [1, 2, 3];
// nums.push(4); // This line is commented out
console.log(nums[1]);
AError: Cannot read property
Bundefined
C2
D3
Attempts:
2 left
💡 Hint
Readonly arrays allow reading elements but not modifying them.
Predict Output
intermediate
2:00remaining
What error does this code raise when trying to modify a readonly array?
What error will this TypeScript code produce when compiled?
Typescript
const letters: readonly string[] = ['a', 'b', 'c'];
letters[0] = 'z';
AError: Index signature in type 'readonly string[]' only permits reading
BTypeError at runtime
CSyntaxError
DNo error, array modified
Attempts:
2 left
💡 Hint
Readonly arrays prevent assignment to elements.
🔧 Debug
advanced
2:00remaining
Why does this code fail to compile when using readonly arrays?
Identify the reason why this TypeScript code does not compile.
Typescript
function addItem(arr: readonly number[], item: number) {
  arr.push(item);
  return arr;
}
AReadonly arrays do not have the push method
BFunction parameters cannot be readonly
CCannot return arrays from functions
DMissing return type annotation
Attempts:
2 left
💡 Hint
Readonly arrays do not allow modification methods.
🧠 Conceptual
advanced
2:00remaining
Which statement about readonly arrays in TypeScript is true?
Choose the correct statement about readonly arrays.
AReadonly arrays are mutable but cannot be reassigned to a new array
BReadonly arrays can be modified using map or filter methods
CReadonly arrays allow push but not pop
DReadonly arrays prevent any modification including element reassignment and push/pop
Attempts:
2 left
💡 Hint
Think about what readonly means for arrays.
Predict Output
expert
2:00remaining
What is the output of this code mixing readonly and mutable arrays?
What will be the output of this TypeScript code?
Typescript
const original: number[] = [1, 2, 3];
const readOnlyView: readonly number[] = original;
original.push(4);
console.log(readOnlyView.length);
AError: Cannot push to original
B4
C3
DError: Cannot assign original to readonly array
Attempts:
2 left
💡 Hint
Readonly arrays are views, not copies.