Can you explain why I can change const array in TypeScript, but other types I cant change?
Example:
let readOnlyArray: readonly string[] = ["Apple", "Orange", "Banana"];
console.log(readOnlyArray);
readOnlyArray[0] = "TOMATO"; // !ERROR because array has read only type
const constArray: string[] = ["Apple", "Orange", "Banana"];
console.log(constArray); // Output: [ 'Apple', 'Orange', 'Banana' ]
constArray[0] = "TOMATO";
console.log(constArray); // Output: [ 'TOMATO', 'Orange', 'Banana' ]
But, when I try to change other type of const I get error, because I cant change const.
const apple: string = "apple";
apple = "TOMATO"; // !ERROR - you cant change const
const myNum: number = 1;
myNum = 2; // !ERROR - you cant change const
// etc...
>Solution :
This is a good question! If you’re curious for a more in-depth answer, check out the reply here: Why can I change a constant object in javascript.
Otherwise I can give you a really short summary.
Setting a variable as a constant only guarantees two things:
- The constant cannot change through re-assignment
- The constant cannot be re-declared
Since in this case you are doing neither of those things, no error will be generated!