Skip to content

noUncheckedIndexAccess behavior with for...in loops with a constant #45169

Closed
@charles-toller

Description

@charles-toller

Bug Report

Using a for...in loop with a constant key variable errors with noUncheckedIndexAccess.

🔎 Search Terms

for...in
noUncheckedIndexAccess
for(const in)

🕗 Version & Regression Information

Seen in v4.1.5 (oldest playground with noUncheckedIndexAccess) and next (v4.4.0-dev.20210723 at time of writing)

⏯ Playground Link

Playground link with relevant code

💻 Code

type A = {[key: string]: number};
declare var a: A;
for (const key in a) {
    const value: number = a[key];
}

🙁 Actual behavior

Error:

Type 'number | undefined' is not assignable to type 'number'.
  Type 'undefined' is not assignable to type 'number'.(2322)

🙂 Expected behavior

No error, key is in object by the for...in loop and clearly isn't modified as variable is const

Activity

RyanCavanaugh

RyanCavanaugh commented on Jul 23, 2021

@RyanCavanaugh
Member

This is the documented behavior of the flag; see #39560. It's entirely possible to read an undefined out of this loop if mutation were to occur to the object prior to the read.

typescript-bot

typescript-bot commented on Jul 29, 2021

@typescript-bot
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @andrewbranch@RyanCavanaugh@charles-toller@typescript-bot

        Issue actions

          `noUncheckedIndexAccess` behavior with for...in loops with a constant · Issue #45169 · microsoft/TypeScript