Skip to content
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

Type of element selected from (potentially) empty array #47060

Closed
jaksenko opened this issue Dec 8, 2021 · 5 comments
Closed

Type of element selected from (potentially) empty array #47060

jaksenko opened this issue Dec 8, 2021 · 5 comments

Comments

@jaksenko
Copy link

jaksenko commented Dec 8, 2021

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.

@whzx5byb
Copy link

whzx5byb commented Dec 8, 2021

See #39560

@jaksenko
Copy link
Author

jaksenko commented 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
Copy link
Contributor

I still think this report is valid because TS currently doesn't follow JS specification.

But the problem is solved. That's exactly what the mentioned flag is for.

@jaksenko
Copy link
Author

jaksenko commented 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.

@jaksenko jaksenko closed this as completed Dec 8, 2021
@RyanCavanaugh
Copy link
Member

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.

This is equally true of objects? Anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants