"noUncheckedIndexedAccess"

Adds undefined to the type of an index read, because an element at that index may not exist.

On this page

Example

#
JSON
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true
  }
}

Definition and usage

#

By default, reading from an array by index (scores[3]) or from an object through an index signature (prices[course]) has the element type, e.g. number. In a running program, though, such a read can return undefined. The noUncheckedIndexedAccess option appends | undefined to the type, so the compiler forces you to handle the missing element.

The option isn’t part of the strict group, and you have to enable it separately. It doesn’t apply to fields declared by name in a type, or to tuples read with a constant index (pair[0] for the type [string, number]). A for...of loop and methods like map() still give you elements of the plain type.

After enabling it in an existing project, you’ll find quite a few places to fix, usually handled with ??, ?., or a condition. In return, a whole class of “Cannot read properties of undefined” errors goes away. Since TypeScript 5.9, the option is enabled in the file created by tsc --init.

Syntax

#
Syntax
"noUncheckedIndexedAccess": true

More examples

#
Reading from an array
TypeScript
const scores = [72, 95, 88]
const fourth = scores[3]
// const fourth: number | undefined

// fourth.toFixed(1)
// Error: 'fourth' is possibly 'undefined'.

console.log((fourth ?? 0).toFixed(1))
console.log(scores[0]?.toFixed(1))
Result
0.0
72.0
A dictionary with arbitrary keys
TypeScript
const prices: Record<string, number> = { html: 49, python: 79 }

function priceLabel(course: string): string {
  const price = prices[course]
  // const price: number | undefined
  return price === undefined ? 'not available' : `${price} PLN`
}

console.log(priceLabel('python'))
console.log(priceLabel('rust'))
Result
79 PLN
not available

Good practices

#
  • The check scores.length > 0 doesn’t narrow the type of scores[0]. Store the element in a variable and check that: const first = scores[0]; if (first !== undefined) 
.
  • Instead of a loop with an index, use for...of, map(), or forEach(). The element then has the plain type, without | undefined.
  • In an existing project, turn the option on in a separate branch and fix errors in batches. Most fixes just add ?? or a condition.

Related entries

#

Spotted a mistake or missing an example? Write to us.