Table of contents
- 1. Potential errors with array ranges
- 2. Limitations of checking array length
- 3. Using noUncheckedIndexedAccess for code safety
- 4. Preventing errors with index signatures
The noUncheckedIndexedAccess compiler option is designed to help catch potential errors caused by accessing arrays or tuples with possibly undefined
or out-of-bounds indices. When this option is enabled, TypeScript assumes that indexed accesses can result in undefined values and requires developers to handle such cases explicitly.
Potential errors with array ranges
For example, consider the following code:
1 |
|
If noUncheckedIndexedAccess
is disabled, TypeScript assumes that value
will always yield a User
, even though array
is empty. This can result in a runtime error when trying to access an undefined value.
Limitations of checking array length
Checking the array length alone is not sufficient to ensure code safety because arrays can have a length without containing any values, as demonstrated by the following code:
1 |
|
Using noUncheckedIndexedAccess
for code safety
Enabling the noUncheckedIndexedAccess
option in your TypeScript configuration provides code safety by flagging potential undefined array or tuple accesses with a TS18048 error. To handle such cases and prevent crashes, you can use the optional chaining operator (?.
) in TypeScript:
1 |
|
Preventing errors with index signatures
Enabling noUncheckedIndexedAccess
provides an additional advantage when working with index signatures. Index signatures allow arbitrary property names, as demonstrated in the options
object below. With the compiler checking index access, you can avoid type errors and ensure safer code execution:
1 |
|