5 ms·
I haven't used typescript much but it's surprising to me that you can pass a `const` value to as an argument which is not `ReadOnly`. Does `const` not really me
by milliams 5y ago
I haven't used typescript much but it's surprising to me that you can pass a `const` value to as an argument which is not `ReadOnly`. Does `const` not really mean anything?
- hajile 5y ago`const` means a constant pointer, but doesn't guarantee that the data it points to will remain constant. In practice, functions, numbers, bigint, symbols, booleans, strings, regex literals, null, and undefined are all immutable. Since you can't change the value, a const to one of these guarantees the value will never be modified. Objects, arrays (actually just objects with a different constructor), maps, sets, TypedArrays (real arrays), etc are different. You can be guaranteed that you will be pointing to the same object instance because there's no way to swap out data at a location in memory like there is in low-level languages (yay GCs). The entries inside the hashmap or array can be modified though. Calling `Object.freeze()` will lock down an array or object with some caveats. Sub-objects will still be modifiable (though you could recursively freeze) and this doesn't work for Map or Set (their properties like get/set/forEach will be frozen, but not the actual data) and it will throw if used on a typed array.
- keawade 5y agoThat’s a JavaScript specific nuance that typescript inherits. ‘const’ declares a variable with an immutable reference, not an immutable value. If you’re referencing a simple literal like a string or a number that’s effectively the same thing but for objects (and arrays under the hood of JavaScript are fancy objects) while the reference to your given object is constant, the properties of that objects are still mutable.
- shadowgovt 5y agoCorrect. This is a thing you can do in JavaScript (and TypeScript) that sometimes trips new people up but is exactly what these keywords mean: const foo = []; foo.push(1,2,3);
- AtNightWeCode 5y agoSame in a lot of programming languages. A common source of errors too. Maybe it is a bit more confusing in JS simply cause people have been taught to make an active choice between var, let and const.
- Xenoamorphous 5y agoSame as Java’s final, isn’t it. You can use final when declaring a reference to an object but that doesn’t make the object itself immutable, just the reference itself.
- fenomas 5y ago"const foo = bar" just means that foo can't be reassigned to some other value. It doesn't say anything about bar.