|
Which "const" do you mean? The one in front of a variable declaration cannot make the array itself constant. That's because that "const" only refers to that variable itself, which is just a pointer (except for the primitive types). The variable declaration "const" means this variable cannot be changed to point to a different object. It says nothing about the thing it points to and that is how that keyword was designed in this language. It's Javascript (ECMAscript), not Typescript. On the other hand, using Typescript (which only adds type annotations but the actual code is ECMAscript apart from very few small things such as "enums"), you can append "as const" after an array though as type annotation, as in const arr = [1,2,3] as const;
// Type error: "Property 'push' does not exist on type 'readonly [1, 2, 3]'"
arr.push(5);
Which is the same as Readonly<type>.This "as const" annotation can be used for any object, not just for arrays. Of course, it can only guard against known methods of mutating an object, such as direct write access to properties and known mutating function calls for known object types such as the built-in ones (Array, Set, Map, etc., each one needs the definitions for the readonly-version of its type in the Typescript-bundled type library). |
Surely they could have gone with, like, `final` or `immutable` instead..? I'm sure they had their reasons. But seems rough.