"noUncheckedIndexedAccess"
Adds undefined to the type of an index read, because an element at that index may not exist.
Example
#{
"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
#"noUncheckedIndexedAccess": trueMore examples
#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))0.0 72.0
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'))79 PLN not available
Good practices
#- The check
scores.length > 0doesnât narrow the type ofscores[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(), orforEach(). 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
#- "strict"Turns on a set of the most important, rigorous compiler checks.
- "strictNullChecks"Treats null and undefined as separate types, forcing you to handle them.
- Index signatureA description of objects with arbitrary keys and values of one type.
- Arrays: number[] and Array<T>Array types, where every element has the same type.
- Record<Keys, Type>Creates an object type with given keys, where every value has the same type.
Spotted a mistake or missing an example? Write to us.