Skip to content

New Rule: no-unsafe-array-access #65

@pertrai1

Description

@pertrai1

Research Evidence

From empirical LLM bug studies: Missing edge cases account for ~15% of LLM bugs. The "Understanding Code Generation Errors" study (557 bugs) lists "missing condition" as a top semantic error. LLMs frequently access array elements without checking if the array is empty.

Description

Prevent accessing arr[0], arr[arr.length - 1], or destructuring const [first] = arr without first checking that the array is non-empty.

Examples

Bad

const items = getItems();
const first = items[0]; // No length check

const [head, ...tail] = results; // No emptiness check

function getFirst(arr: string[]) {
  return arr[0]; // Could be undefined
}

Good

const items = getItems();
if (items.length > 0) {
  const first = items[0];
}

const [head, ...tail] = results.length > 0 ? results : [defaultValue];

function getFirst(arr: string[]): string | undefined {
  return arr.length > 0 ? arr[0] : undefined;
}

Detection Approach

  • Flag arr[0] and arr[arr.length - 1] when not preceded by a length/emptiness check in the same scope
  • Flag array destructuring const [x] = arr without a guard
  • Consider only flagging when the array type doesn't include undefined in its element type (to avoid flagging when noUncheckedIndexedAccess is enabled)

Scope Considerations

  • TypeScript's noUncheckedIndexedAccess handles the type-level concern, but many projects don't enable it
  • This rule focuses on the runtime safety pattern, not the type system
  • Should respect existing guard patterns: if (arr.length), arr?.length > 0, arr.length !== 0, etc.

Priority

High — one of the most specific, detectable edge-case patterns from the research. Directly derived from splitting the overly broad require-edge-case-handling proposal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthigh-valueCatches real bugs or enforces critical patternsneeds-analysisRequires overlap/scope analysis before implementationruleRelated to an ESLint rule (new or existing)

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions