why does typescript assume array element lookup won’t be undefined?

Comments from @jonrsharpe and @shinigami helped me understand this! Paraphrasing:

  1. Arrays are basically { [index: number]: T }, where every value of index is assumed to have a defined T value. One can use a tuple type if a specific length is expected.

  2. But with the flag --noUncheckedIndexedAccess (to be included in TypeScript 4.1), the behavior will match my original expectation. In particular:

Under this new mode, every property access (like foo.bar) or indexed access (like foo[“bar”]) is considered potentially undefined.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top