← 中文资源

简体中文版本

at() 让索引访问带上 undefined

at() 对越界和负索引如实返回 T | undefined,比方括号取值的乐观类型诚实;用 ?? 兜底处理一次,越界分支就再也藏不住。

阅读英文原文

运行结果

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

bracket[3]: undefined | typeof: undefined
at(9): undefined | typeof: undefined
at(-1): deploy
at(-4): undefined
deploy
(no stage)
(no stage)

实现说明

逻辑集中在函数 label里。

使用要点

  • 每一步打印都带着自己的标签:bracket[3]:、at(9):、at(-1):。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 label。

主签名形如 function label(value: string | undefined)

核心语句

return value ?? '(no stage)';

代码示例

// Bracket indexing is optimistic about bounds; at() answers with T | undefined.
const stages: string[] = ['build', 'test', 'deploy'];

const fourth = stages[3]; // typed string, actually undefined at runtime
console.log('bracket[3]:', fourth, '| typeof:', typeof fourth);

const missing = stages.at(9); // typed string | undefined, honestly undefined
console.log('at(9):', missing, '| typeof:', typeof missing);

// Negative indexes read from the end and share the same T | undefined type
console.log('at(-1):', stages.at(-1));
console.log('at(-4):', stages.at(-4));

// Handle the undefined branch once, then reuse the helper
function label(value: string | undefined): string {
  return value ?? '(no stage)';
}

console.log(label(stages.at(-1)));
console.log(label(stages.at(-4)));
console.log(label(stages[3]));