Sub topic 3
Reading Array Elements and `noUncheckedIndexedAccess`
This chapter assumes that you know JavaScript arrays, TypeScript annotations, and union types. The focus is reading an element by index and handling the possibility that no element exists.
What an array index means
An array index is a number inside square brackets. JavaScript starts counting at zero:
const scores: number[] = [90, 85, 72];
const first = scores[0]; // 90
const missing = scores[10]; // undefined at runtimeThe index 0 selects the first element. The index 10 is outside the array, so JavaScript returns undefined.
By default, TypeScript types both first and missing as number. This is convenient, but it does not fully describe the runtime behavior. A later operation can fail:
const scores: number[] = [90, 85, 72];
const score = scores[10];
console.log(score.toFixed(1)); // Runtime errorTypeScript allows this code by default because score is treated as a number.
Enabling `noUncheckedIndexedAccess`
The noUncheckedIndexedAccess compiler option adds undefined to the type returned by an unchecked array index.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}With this option, the previous example produces a type error. The type of scores[10] is number | undefined.
const scores: number[] = [90, 85, 72];
const score = scores[10];
if (score !== undefined) {
console.log(score.toFixed(1));
} else {
console.log("No score at that index");
}The condition is a type guard. It checks the value and narrows score from number | undefined to number inside the first branch.
| Expression | Default type | With `noUncheckedIndexedAccess` | Column | Column |
|---|---|---|---|---|
| `scores[0]` | `number` | `number \ | undefined` | |
| `scores[index]` | `number` | `number \ | undefined` | |
| `scores.find(...)` | `number \ | undefined` | `number \ | undefined` |
The option also affects arrays accessed through variables whose indexes are not known to be valid. It encourages code to handle missing elements explicitly.
Reading safely
A helper function can make repeated index checks clearer:
function getScore(scores: number[], index: number): number | undefined {
return scores[index];
}
const scores = [90, 85, 72];
const score = getScore(scores, 1);
if (score === undefined) {
console.log("Score not found");
} else {
console.log(score.toFixed(1));
}Returning number | undefined tells callers that the requested position might not exist. A caller can then choose a fallback:
const score = getScore(scores, 10) ?? 0;
console.log(score.toFixed(1));The nullish coalescing operator ?? uses 0 only when the left side is null or undefined.
Tuples and known positions
Tuples describe a fixed number of positions. TypeScript can therefore check some indexes more precisely:
const point: [number, number] = [10, 20];
const x = point[0]; // number
const y = point[1]; // number
// const z = point[2]; // Error: no element at index 2An array says, “this collection can contain many values of one type.” A tuple says, “these exact positions exist and have these types.”
Common mistake
Checking only the array length does not prove that an arbitrary value is a valid integer index. Negative numbers, decimals, and indexes beyond the final position can still be invalid. Treat an indexed read as potentially missing unless the type or your validation guarantees otherwise.
Exercise
With noUncheckedIndexedAccess enabled, what is the type of items[3] when items has type string[], and how should you use it safely?
Show answer
Its type is string | undefined. Check whether the value is undefined before using it as a string, or provide a fallback with ??.