Open In App

TypeScript Object The ReadonlyArray Type

In this article, we are going to learn about Object The ReadonlyArray Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the ReadonlyArray<T> type is used to create an immutable (read-only) array of elements of type T. It ensures that once an array is defined as ReadonlyArray, you cannot modify its contents or length. This is useful when you want to prevent accidental modifications to an array’s values.

Syntax



const myArray: ReadonlyArray<T> = [...]; 
// or
const myArray: readonly T[] = [...];

Where-

Example 1: In this example, ‘numbers’ is declared as a ReadonlyArray<number>, so any attempts to modify the array (e.g., using push or assigning new values to elements) will result in TypeScript errors.






const numbers: ReadonlyArray<number> = [1, 2, 3, 4, 5];
console.log(numbers)
  
// You can assign readonly array by this also
//const str: readonly string[] = ['hello' , 'geekforgeeks']
//console.log(str)
  
// Attempting to modify the read-only
// array will result in a TypeScript error:
// numbers.push(6); // Error: Property 'push' 
//does not exist on type 'readonly number[]'.
// numbers[0] = 0;
// Error: Index signature in type 
//'readonly number[]' only permits reading.

Output:

Example 2: In TypeScript, the assignability between a regular array (T[]) and ReadonlyArray<T> is bidirectional. This means you can assign a regular array to a ReadonlyArray<T> and vice versa. In this example, regularArray is a regular array of numbers. readonlyArray is a ReadonlyArray<number> assigned the value of regularArray. You can assign a regular array to a ReadonlyArray. You can also assign a ReadonlyArray to a regular array, and modifying the regular array is allowed after the assignment.




const regularArray: number[] = [1, 2, 3];
  
// You can assign a regular 
//array to a ReadonlyArray
const readonlyArray: ReadonlyArray<number> = regularArray;
  
// You can access elements from a ReadonlyArray
console.log(readonlyArray[0]); // Outputs: 1
const anotherReadonlyArray: ReadonlyArray<number> = [4, 5, 6];
  
// You can also assign a
// ReadonlyArray to a regular array
const regularArray2: number[] = [...anotherReadonlyArray];
  
// Attempting to modify a regular array after
// assignment from a ReadonlyArray is allowed
regularArray2.push(7);
console.log(regularArray2); // Outputs: [4, 5, 6, 7]

Output:


Article Tags :