Closed
Description
Bug Report
π Search Terms
array index element undefined
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about type of element selected from (potentially) empty array
β― Playground Link
Playground link with relevant code
π» Code
const ary: string[] = [];
const firstElement = ary[0];
// `firstElement`'s type is `string` while it should be `string | undefined`
// or even better `undefined` since that can be deduced from the line above.
π Actual behavior
firstElement
is of type string
.
π Expected behavior
firstElement
should be of type string | undefined
or undefined
if that can be deduced.
Activity
whzx5byb commentedon Dec 8, 2021
See #39560
jaksenko commentedon Dec 8, 2021
Thanks, I didn't know about the flag, but as soon as I turned it on I got bombarded with TS errors because the flag deals not only with arrays but also with objects. And I import a lot of objects that aren't typed until I cast them (json, css, ...).
Anyway, I still think this report is valid because TS currently doesn't follow JS specification. In JS, if index doesn't exist, it returns
undefined
.MartinJohns commentedon Dec 8, 2021
But the problem is solved. That's exactly what the mentioned flag is for.
jaksenko commentedon Dec 8, 2021
You are right, I guess I just don't agree with the implementation that mixes arrays with objects, but that's another story. Thank you for pointing me to the flag.
RyanCavanaugh commentedon Dec 8, 2021
This is equally true of objects? Anyway.