Typescript: accessing an array element does not account for the possibility of undefined return values
PRE-TS4.1 ANSWER:
You have discovered that index signatures don't add | undefined
to the element type the way that optional properties do. It has been suggested to create a compiler option that would do this. You can read the comments in that suggestion; they link to other issues, but the consensus is that the high false positive rate would make it nearly useless.
It is also mentioned that you have the ability to manually add | undefined
to the element type:
const list: (Item | undefined)[] = [{ id: 'a' }, { id: 'b' }];
which will behave as you expect, without affecting the whole language.
UPDATE for TS 4.1:
TypeScript 4.1 will introduce a --noUncheckedIndexedAccess
compiler flag that implements the suggestion in microsoft/TypeScript#13778 to account for undefined
in this way. Note that the feature will not be enabled as part of the --strict
set of compiler options and is being called "pedantic index signatures" because it will end up complaining about the possibility of undefined
in situations where programmers might not expect or desired it.
Hope that helps. Good luck!