实现说明
逻辑集中在函数 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]));