1

Why does TypeScript think an object in an array is possibly undefined when noUncheckedIndexedAccess configuration is enabled even after the length is checked?

Playground

interface Item {
    x: number
}

declare var items: Item[]

if(items.length === 2) { // Length is checked
    const [first, second] = items

    first.x // Error: Object is possibly undefined
    second.x // Error: Object is possibly undefined
}

I would expect the length === 2 to "prove" to TypeScript that the object in the first and second position of the array are present.

Daniel X Moore
  • 14,637
  • 17
  • 80
  • 92

0 Answers0