Skip to content

Improve noUncheckedIndexedAccess with array.lengthΒ #53678

@yw662

Description

@yw662

Suggestion

πŸ” Search Terms

noUncheckedIndexedAccess, length, for loop

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Make noUncheckedIndexedAccess work slightly better with array.length

πŸ“ƒ Motivating Example

eg. in the code below,

const array: number[] = [0, 1, 2]
let n = 0
for(let i = 0; i < array.length; i++) {
  n = n + array[i]
}

will cause false positive with noUncheckedIndexedAccess saying array[i] can be undefined. However it cannot since we have condition i < array.length.

And another example,

function f(arr: number[]) {
  if(arr.length < 1) {
    ...
  } else {
    const v: number = arr[0]
    ...
  }
}

We have arr.length >= 1 at the very line so arr[0] is number for sure.

Doing math in type checks is generally troublesome but if it is restricted to some particular cases it can be very helpful.

πŸ’» Use Cases

noUncheckedIndexedAccess are not used very much because it can cause lots of false positives. Fixing at least some of the issues can make it much more useable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DeclinedThe issue was declined as something which matches the TypeScript visionSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions