Sub topic 3
Reading elements and noUncheckedIndexedAccess
This chapter assumes you know basic JavaScript arrays, basic TypeScript annotations, and union types such as number | undefined. It also assumes you have met T[] and array literal inference in the earlier chapters. Here the question is what type you get when you read one element out of an array, and why that type can be wrong.
What the compiler does by default
When you read xs[i] from a number[], TypeScript gives you number. It does not check that i is in range. The array type says only "a list of numbers of unknown length", and the compiler does not track length.
const scores: number[] = [90, 85, 72];
const first = scores[0]; // number
const tenth = scores[9]; // number, but the value at runtime is undefined
console.log(first.toFixed(1)); // prints 90.0
console.log(tenth.toFixed(1)); // compiles, then throws TypeError at runtimeThe last line is the problem. The compiler believes tenth is a number, so it allows .toFixed. At runtime JavaScript returns undefined for a missing index, and the call fails.
The default is a trade-off. Many programs index inside loops where the index is known to be valid. Marking every read as possibly undefined would force checks in code that is already correct.
The same gap exists for index signatures such as Record<string, number> or { [key: string]: number }. Reading a key that does not exist returns undefined, but the type says number.
Turning on noUncheckedIndexedAccess
The noUncheckedIndexedAccess compiler option closes this gap. It adds undefined to the type of any read that goes through an index signature, which includes array element access.
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true
}
}The option is not part of strict. You must enable it separately, and it needs strictNullChecks (which strict includes) to have any effect.
With it on, the earlier example changes:
const scores: number[] = [90, 85, 72];
const first = scores[0]; // number | undefined
// console.log(first.toFixed(1));
// Error: 'first' is possibly 'undefined'.
if (first !== undefined) {
console.log(first.toFixed(1)); // first is number here
}The first element exists at runtime, but the compiler cannot know that. It makes you prove it.
What the flag changes and what it leaves alone
The flag affects reads that go through an index signature. It does not affect everything that touches an array.
| Expression | Without the flag | With the flag | Column | Column |
|---|---|---|---|---|
| `xs[0]` on `number[]` | `number` | `number \ | undefined` | |
| `xs[i]` on `number[]` | `number` | `number \ | undefined` | |
| `const [a] = xs` on `number[]` | `number` | `number \ | undefined` | |
| `rec["k"]` on `Record<string, number>` | `number` | `number \ | undefined` | |
| `t[0]` on `[number, string]` | `number` | `number` | ||
| `for (const x of xs)` | `number` | `number` | ||
| `xs.map((x) => x)` | `number` for `x` | `number` for `x` | ||
| `xs.at(0)` | `number \ | undefined` | `number \ | undefined` |
Four points follow from the table.
- Tuples with fixed positions are not affected, because the compiler knows exactly which positions exist. Reading
t[2]on a two-element tuple is already an error, with or without the flag. - Iteration is not affected.
for...of,map,filter,forEachandreduceonly visit elements that exist, so their callbacks receiveT. - Array destructuring of a plain array is affected, because it reads by index under the hood.
at()already returnsT | undefinedin the standard library types. It needs alibsetting ofes2022or later.
Here is the same flag applied to an object used as a dictionary:
const ages: Record<string, number> = { ada: 36, linus: 54 };
const ada = ages["ada"]; // number | undefined
const grace = ages.grace; // number | undefined
const adaAge = ada ?? 0; // numberWays to handle `T | undefined`
Once the flag is on, you pick a strategy for each read. They fit different situations.
| Strategy | Example | Use when |
|---|---|---|
| Narrow with a check | `if (x !== undefined) { ... }` | You want different behavior when the element is missing |
| Default value | `xs[0] ?? 0` | A sensible fallback exists |
| Optional chaining | `users[0]?.name` | You read a property and `undefined` is an acceptable result |
| Iterate instead | `for (const x of xs)` | You wanted every element anyway |
| Non-null assertion | `xs[0]!` | You know better than the compiler, and a wrong guess is acceptable |
A short example of the first three:
interface User {
name: string;
}
const users: User[] = [{ name: "Ada" }, { name: "Linus" }];
const firstUser = users[0];
if (firstUser !== undefined) {
console.log(firstUser.name);
}
const firstName = users[0]?.name ?? "nobody"; // string
console.log(firstName);Prefer iteration to index loops
A classic index loop becomes noisy under the flag, because every xs[i] is possibly undefined, even though i < xs.length guards it.
function firstPositive(xs: number[]): number | undefined {
for (const x of xs) {
if (x > 0) {
return x;
}
}
return undefined;
}
console.log(firstPositive([-2, 0, 7, 3])); // 7The for...of version has no index and no check. If you need the index too, use xs.entries(). It yields [number, T] pairs, and T is not widened with undefined.
const letters: string[] = ["a", "b", "c"];
for (const [i, letter] of letters.entries()) {
console.log(i, letter.toUpperCase());
}Common errors and gotchas
A length check does not narrow
The compiler does not connect length to index validity.
function head(xs: number[]): number {
if (xs.length > 0) {
// return xs[0]; // Error: Type 'number | undefined' is not assignable to type 'number'.
}
return -1;
}Check the value itself, not the length.
function head(xs: number[]): number {
const first = xs[0];
if (first !== undefined) {
return first;
}
return -1;
}Assigning the read to a local const is the most reliable pattern. It narrows cleanly, and it avoids reading the array twice.
Narrowing a repeated read is fragile
TypeScript can narrow xs[0] after if (xs[0] !== undefined) when the index is a literal. It can also narrow xs[i] when i is a const. With a let index, such as a classic loop counter, the narrowing does not hold. A function call between the check and the use also resets it, because the call might change the array. The local const avoids all of these cases.
Arrays that legitimately contain `undefined`
If the element type already includes undefined, the flag cannot tell "missing" from "present but undefined".
const slots: (string | undefined)[] = ["a", undefined, "c"];
const second = slots[1]; // string | undefined, and it is present
const ninth = slots[8]; // string | undefined, and it is missingIf the difference matters, compare the index against length. A null placeholder, or a different data structure such as a Map, makes the intent clearer.
The non-null assertion is a promise, not a check
xs[0]! removes undefined from the type and emits no runtime check. If the array is empty, you get the same TypeError as before. Reserve it for cases where a nearby invariant makes the element certain. If you need it in many places, write a helper.
function getAt<T>(xs: readonly T[], index: number): T {
if (!Number.isInteger(index) || index < 0 || index >= xs.length) {
throw new RangeError(`No element at index ${index}`);
}
return xs[index] as T;
}
const nums = [10, 20, 30];
console.log(getAt(nums, 1)); // 20The helper checks bounds instead of testing for undefined, so it also works for arrays that contain undefined values. The as T cast lives in one place and sits right behind the check that justifies it.
Should you turn it on?
The option catches a real class of runtime errors: undefined read from an empty array, a missing dictionary key, a bad destructure. The cost is extra narrowing at each index read. Most of that cost disappears if you favor for...of, array methods and destructuring from tuples.
For a new project, enable it from the start. For an existing codebase, expect many errors on first enable, mostly in index loops and dictionary lookups. You can fix them in batches by area, or turn the flag on for a new subproject first.
Exercise
With noUncheckedIndexedAccess on, what are the types of a, b and c below, and which of them would be an error if you wrote a.toFixed(1)?
const xs: number[] = [1, 2, 3];
const pair: [number, string] = [1, "x"];
const a = xs[0];
const b = pair[0];
const [c] = xs;
Show answer
a is number | undefined, b is number, and c is number | undefined. Calling a.toFixed(1) is an error ("possibly undefined"), and so is c.toFixed(1). b is safe because a tuple position is known to exist. Reading xs[0] or destructuring a plain array goes through the number index signature, which the flag widens with undefined.
Exercise
Rewrite this function so it compiles with noUncheckedIndexedAccess on, without using !, and so it still returns -1 for an empty array.
function last(xs: number[]): number {
return xs[xs.length - 1];
}
Show answer
Assign the read to a local constant and narrow it, or use at(-1) with a default:
function last(xs: number[]): number {
const value = xs[xs.length - 1];
return value !== undefined ? value : -1;
}
Equivalent: return xs.at(-1) ?? -1; (this needs lib set to es2022 or later). For an empty array, xs[-1] is undefined, so both versions return -1.