P粉1945410722023-08-25 11:31:36
This is intentional behavior. View the long discussion on this issue on the TypeScript GitHub repository
Your strictNullChecks
is off; try turning it on.
P粉3302320962023-08-25 11:19:47
TypeScript 4.1 introduced a --noUncheckedIndexedAccess
compiler flag that implements the suggestion made in microsoft/TypeScript#13778 to account for this case undefined
. Note that this feature is not enabled as part of the --strict
compilation option set, and is referred to as a "strict index signature" because it emits situations where the programmer may not want or expect Warning about undefined
.
You've discovered that index signatures do not add | undefined
to element types like optional properties do. The suggestion to create a compiler option to achieve this was made at microsoft/TypeScript#13778. You can read the comments in that suggestion; they link to other questions, but the consensus is that the high error rate almost makes it useless.
also mentioned that you can manually add | undefined
to the element type:
const list: (Item | undefined)[] = [{ id: 'a' }, { id: 'b' }];
This will work as you expect without affecting the entire language.