this post was submitted on 29 Jul 2025
-1 points (44.4% liked)

Programming

14121 readers
1 users here now

All things programming and coding related. Subcommunity of Technology.


This community's icon was made by Aaron Schneider, under the CC-BY-NC-SA 4.0 license.

founded 2 years ago
MODERATORS
 

TypeScript does not throw an error at compile time for accessing an out-of-bounds index. Instead, it assumes that the value could be one of the types defined in the array (in this case, 1 or 2) or undefined.

TypeScript automatically infers the type of a value accessed from an array, even if that access is out of bounds. It assumes that the value could be one of the defined types or undefined, which can lead to confusion if you expect stricter enforcement of valid indices.

I just spent the last 2 hours trying to understand why I was getting a valid type from something that shouldn't have been valid.

I think that the hate that JavaScript receives is well deserved, at least coming from Rust this is an absolute nightmare.

you are viewing a single comment's thread
view the rest of the comments
[–] hperrin@lemmy.ca 3 points 4 days ago (1 children)

I’m sorry but your problem here is solely with JavaScript, not TypeScript. TS is right to assign that type to the value, because that is perfectly valid JS, and that is the type you should expect.

It’s not hard to check for undefined and there are absolutely times you wouldn’t want an error to be thrown, so this is just you having a preference, and judging an entire language based on your preference.

There are actual reasons to dislike how JS works, out of bounds array access returning undefined is not one of them.

[–] hperrin@lemmy.ca 2 points 4 days ago (1 children)

To add to my own comment, I want to remind you that JavaScript was designed to power websites, and having an entire website break because an array didn’t have anything in it yet is probably worse than the alternative.

A lot of JS’ decisions actually make sense when you understand its history. That doesn’t mean it’s a great language, but it’s undeniably good at fulfilling its original purpose, making websites interactive in myriad different browser implementations.

[–] dontblink@feddit.it 4 points 4 days ago (1 children)

Yes you're probably right, I definitely have bias and the time spent tryna fix the bug influenced this..

Thanks

[–] hperrin@lemmy.ca 3 points 3 days ago

It’s refreshing to have a nice reply online! Thank you, too. :)