Skip to content

let indexes using noUncheckedIndexedAccess in TS 5.5.2Β #58972

Closed

Description

πŸ”Ž Search Terms

"array", "noUncheckedIndexedAccess", "5.5"

πŸ•— Version & Regression Information

  • This changed between versions 5.4.5 and 5.5.2

⏯ Playground Link

https://www.typescriptlang.org/play/?noUncheckedIndexedAccess=true&noUnusedLocals=true&noUnusedParameters=true&ts=5.5.2#code/MYewdgzgLgBAhgLhmArgWwEYFMBOBtAXRgF4Y8BGAGhgCZqBmAgbgCgAbLWASyVU1xIxyrFlwBmACigBPAA5YQY+Hi5Fi6mACI+2HJoCULGMeWqA1GaA

πŸ’» Code

const a: number[] = [1, 2, 3];
let i: number = 1;

if(typeof a[i] === "number")
    a[i]++

πŸ™ Actual behavior

Typescript reports the following error:

Object is possibly 'undefined'.(2532)
const a: number[]

πŸ™‚ Expected behavior

It should not report an error for such cases

Additional information about the issue

This obviously requires noUncheckedIndexedAccess to be enabled in the tsconfig.

This only happens when the variable used to access the array is non const (let in this case).

I think that TS 5.5 actually fixed the original behavior because in 5.4 if we remove the check:

const a: number[] = [1, 2, 3];
let i: number = 1;
a[i]++

TS does not raise the same error (which would be expected as a[i] could be undefined).
The current workaround:

const j = i;
if (typeof digits[j] === "number") {
  digits[j]++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

    Issue actions