Skip to content

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

Closed
@jaksenko

Description

@jaksenko

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

whzx5byb commented on Dec 8, 2021

@whzx5byb

See #39560

jaksenko

jaksenko commented on Dec 8, 2021

@jaksenko
Author

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

MartinJohns commented on Dec 8, 2021

@MartinJohns
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

jaksenko commented on Dec 8, 2021

@jaksenko
Author

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

RyanCavanaugh commented on Dec 8, 2021

@RyanCavanaugh
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @MartinJohns@whzx5byb@RyanCavanaugh@jaksenko

        Issue actions

          Type of element selected from (potentially) empty array Β· Issue #47060 Β· microsoft/TypeScript