3 ms·
Array access is a good example. Many type-safe languages throw an exception if you attempt to access an element in an array that is out of bounds but javascrip
by nitram1 7y ago
Array access is a good example.
Many type-safe languages throw an exception if you attempt to access an element in an array that is out of bounds but javascript just returns undefined.
Typescript ignores the fact that accessing an arbitrary element of an array could return undefined. If it did not ignore this fact then it would force you to deal with the potential undefined value retrieved from any array access (i.e you'd need to write a runtime check)
- wwwigham 7y agoIndex unsafety w.r.t. bounds and `undefined` is something TS would like to fix; but it's not ergonomic to fix until there are, something like automatic refinement range types applied to array length fields. Without it, TS'd get in the way, demanding `undefined` checks it almost definitely didn't need. Those range types and their complexity are, ultimately, what currently block TS from making these indexed accesses safer.
- the_gipsy 7y agoSome languages do force you to check any time you access an element. If the rest of the language is in line with this, then it's actually amazing. Option/Maybe types help here, pattern matching lists also let's you make sure you handle all cases. In some instances it makes sense to use a special NonEmptyList type that guarantees there is always at least one element, so you don't need to check.