at() Makes Index Access Undefined Safe
at() returns T | undefined for out-of-range and negative indexes, replacing optimistic bracket indexing with an honest type you can handle once.
Code
// 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]));Output
Captured from a sandboxed run of this snippet in the build pipeline.
bracket[3]: undefined | typeof: undefined
at(9): undefined | typeof: undefined
at(-1): deploy
at(-4): undefined
deploy
(no stage)
(no stage)How it works
The snippet is organized around the function label.
What to watch for
- Every symbol it uses is a language built-in — nothing needs fetching.
Using it
Signature: function label(value: string | undefined)
Output lines are prefixed (bracket[3]:, at(9):, at(-1):), making what each step changes easy to notice.
Key statements worth quoting
return value ?? '(no stage)';
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `label` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.