-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Array lookup should return T | undefined #11122
Comments
IMO, even the strictest type systems tend to allow unsafe array indexing. I think the reason is that a type system should check things that are within its scope of being proven, but without going into the world of proof assistants and formal verification, virtually all array lookups cannot be proven to the type system to be within bounds, so the only practical result is that In other words, there isn't any benefit having a type checker tell you that you failed to prove something without having any means of proving it. |
Duplicate of #9235 |
+1 for this. I've been bitten by this compromise a couple times now so count me in for more safety not less!
If folks are using an unsafe pattern everywhere, maybe that's exactly what should happen. I don't find it particularly onerous. I guess I'd like to see some data on exactly how much impact this would have on existing TypeScript programs before we write it off as making the language unusable.
Right now the sentiment I've seen from TS team is that 1 is negligible, 2 is huge, and 3 is prohibitive. Are there numbers to back up these hunches? Some alternatives to
Looping over a The same could be argued for |
+1000 |
this indeed is a duplicate of #9235. thanks @aluanhaddad. As noted in #9235, this is an intentional behavior, and without this array access would be fairly unusable under |
If authors enable I'm not too familiar with many other type systems, but Scala does have Indeed there would be slightly more boilerplate if we did return Without this there will be a whole class of bugs that TypeScript will never catch. 😒 😢 |
@OliverJAsh Scala is an interesting example but Consider the following Scala: case class Something(name: String)
var xs = Vector[Something]()
def unsafe = {
xs head
}
def safe = {
xs headOption
}
println(safe match {
case Some(s) => s name
case _ => "explicit default"
})
println(unsafe name) If you index into |
I'm currently working around this with a helper function: const arrayHead = <T>(ts: T[]): T | undefined => (
ts[0]
); |
it seems bizarre to me that this code is OK when pretty much all other possible errors are covered:
I vote for |
TS 2.0.3
The type system doesn't know of care about the length of
xs
, so I would expect any lookup in the array to returnT | undefined
.The text was updated successfully, but these errors were encountered: