跳到主要内容
哒哒星球DADA PLANET

Skill · 已公开版本

no-unchecked-indexed-access · 数组越界访问类型检查

检查tsconfig是否启用noUncheckedIndexedAccess,并扫描可能越界的数组与索引签名访问,给出显式判空修复写法。

先看看示例

作者提供的示例,实际效果取决于你的输入和使用工具。

输入

审查数据管道代码,指出tags[0]未判空的问题并改为空值合并写法。

输出

预期交付:未启用标志的提示与越界访问修复建议。(编辑说明,非实际运行结果)

方法说明

---
name: no-unchecked-indexed-access
description: "Use when auditing tsconfig.json for missing safety flags, reviewing code that uses array index access in data processing pipelines, or investigating runtime undefined errors that TypeScript did not catch."
metadata:
  category: javascript
  priority: medium
  difficulty: intermediate
  estimatedTime: "15"
  source: frontendchecklist.io
  url: https://frontendchecklist.io/rules/javascript/no-unchecked-indexed-access
---

# Enable noUncheckedIndexedAccess to catch out-of-bounds array bugs

TypeScript's default behaviour types `array[0]` as `T`, pretending the access is always safe. In reality, the array might be empty or the index might be out of range, leading to silent `undefined` values that cause downstream crashes. Enabling `noUncheckedIndexedAccess` surfaces these potential failures as type errors at compile time, requiring developers to prove the access is safe before the code runs.

## Quick Reference

- Without the flag, array[0] is typed as T even if the array is empty
- noUncheckedIndexedAccess changes array[n] to return T | undefined
- Forces an explicit check before using any array element accessed by index
- Optional chaining and nullish coalescing handle most false positives cleanly

## Check

Check whether noUncheckedIndexedAccess is enabled in the project's tsconfig.json. If not, scan for array index accesses (arr[0], arr[i]) that could fail if the array is shorter than expected.

## Fix

Enable noUncheckedIndexedAccess in tsconfig.json, then update any array index accesses that TypeScript now flags to include an explicit undefined check or use optional chaining before the accessed value is used.

## Explain

Explain what noUncheckedIndexedAccess does, why the default TypeScript behaviour is unsound for array index access, and how optional chaining and Array.at() interact with the flag.

## Code Review

Review all array index accesses in this file (arr[0], arr[i], object[key]). Flag any location where the accessed value is used without a preceding undefined check, even if noUncheckedIndexedAccess is not yet enabled in the project.

---

For full implementation details, code examples, and framework-specific guidance,
see `references/rule.md`.

Rule page: https://frontendchecklist.io/rules/javascript/no-unchecked-indexed-access