0
0
Typescriptprogramming~10 mins

Read-only arrays in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a read-only array of numbers.

Typescript
const numbers: [1] = [1, 2, 3];
Drag options to blanks, or click blank then click option'
Areadonly number[]
BArray<number>
Cnumber[]
Dconst number[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using just number[] allows modification.
Trying to use const inside the type is incorrect.
2fill in blank
medium

Complete the code to prevent modification of the array elements.

Typescript
function printFirst(numbers: [1]) {
  console.log(numbers[0]);
}
Drag options to blanks, or click blank then click option'
AArray<number>
Breadonly number[]
Cnumber[]
Dconst number[]
Attempts:
3 left
💡 Hint
Common Mistakes
Using number[] allows modification inside the function.
Using const in the type is invalid.
3fill in blank
hard

Fix the error by completing the code to assign a read-only array.

Typescript
const arr: readonly string[] = ['a', 'b'];
// Error: Cannot assign to 'arr'
arr = [1];
Drag options to blanks, or click blank then click option'
Aarr
B['a', 'b']
C['c', 'd']
Dnew Array('c', 'd')
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign a new array literal to a read-only variable.
Using new Array() to assign a new array.
4fill in blank
hard

Fill both blanks to create a read-only array and access its first element.

Typescript
const fruits: [1] = ['apple', 'banana'];
const firstFruit: string = fruits[2];
Drag options to blanks, or click blank then click option'
Areadonly string[]
Bnumber
C[0]
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using number as the type for the array.
Trying to access the first element with .length.
5fill in blank
hard

Fill all three blanks to declare a read-only array, map its elements, and prevent modification.

Typescript
const letters: [1] = ['x', 'y', 'z'];
const upperLetters = letters.map(letter => letter.[2]());
// Error if uncommented: letters.[3]('a');
Drag options to blanks, or click blank then click option'
Areadonly string[]
BtoUpperCase
Cpush
Dstring[]
Attempts:
3 left
💡 Hint
Common Mistakes
Declaring the array as mutable string[].
Using a wrong method name instead of toUpperCase.
Trying to use push on a read-only array.