← 中文资源

简体中文版本

无未检查索引访问

开启 noUncheckedIndexedAccess 后,arr[i] 与 record[key] 的类型都是 T | undefined:必须先判空收窄才能使用,.at() 与 ?? 是惯用写法。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

first via guard: 19
bronze rank: unranked
last: 7
doubled: 84

实现说明

演示用的数据放在这几个模块级绑定中:first、rank、last、doubled。 顶层对象字面量把 gold、silver 定成普通值——没有派生,背后也没有导入。

使用要点

  • 跑完文件,输出里会留下标记——first via guard:、bronze rank:、last:。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 文件的状态由几个模块级绑定持有:first、rank、last。

核心语句

const doubled = readings.map((value) => value * 2);

代码示例

// Enable "noUncheckedIndexedAccess": true in tsconfig, then every index
// access becomes T | undefined until you prove the key exists
const readings: number[] = [18, 42, 7];

const first = readings[0]; // number | undefined under the flag
console.log("first via guard:", first === undefined ? "empty" : first + 1);

// Object index access gets the same protection
const ranks: Record<string, number> = { gold: 1, silver: 2 };
const rank = ranks["bronze"]; // number | undefined
console.log("bronze rank:", rank ?? "unranked");

// Array.prototype.at already returns T | undefined, so it reads the same
const last = readings.at(-1);
console.log("last:", last ?? "none");

// After a real check the type narrows - no non-null assertion needed
if (rank !== undefined) {
  console.log("narrowed rank:", rank + 10);
}

// map results are never undefined per element, but indexed reads still are
const doubled = readings.map((value) => value * 2);
console.log("doubled:", doubled[1] ?? "missing");