this post was submitted on 29 Jul 2025
-1 points (44.4% liked)
Programming
14526 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
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
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.
Your
MyUnionTypeis defining an array (of any length) that only contains 1s and 2s. Settingvaluesto[1,2]doesn't narrow the type down to a tuple of 2. I'm not sure why you think it would, but feel free to explain your reasoning and maybe I can clarify your misunderstanding.In any case, it seems like you might be looking to use tuple types