Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement:
TypeScript includes a special type called ReadonlyArray, which is essentially an Array without any methods for mutation. This ensures that you cannot modify your arrays once they have been created:
To verify this concept, I decided to experiment with the sample code below:
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
Upon compiling the aforementioned code snippet into JavaScript, I observed the resulting transformation:
var a = [1, 2, 3, 4];
var ro = a;
ro[0] = 12; // works
ro.push(5); // works
ro.length = 100; // works
a = ro; // works
The compiled JavaScript code indicates that the variable ro
is now mutable within the JavaScript environment, allowing other JavaScript functions to alter its contents. This led me to ponder why TypeScript did not create a derivative subclass of the Array
object specifically tailored for ro
, with the mutable methods removed. Is there something crucial that I am overlooking here?