By enabling the noUncheckedIndexedAccess
option in TypeScript,
we ensure that when accessing object properties with arbitrary keys, the value type includes both the specified type and undefined
.
This behavior is generally appropriate as it aligns with runtime expectations. However, I am interested in specifying that no property should ever return undefined
, thus guaranteeing safe property access.
Here's an example code snippet:
type ArbitraryStringIndexAccess = {
[key: string]: number
}
const object: ArbitraryStringIndexAccess = {}
const value: number = object.property
// Type 'number | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'.
// (2322)
I have attempted to find possible solutions on my own without success. I would appreciate any insights on achieving this goal while maintaining the flag.
Edit:
There seems to be an existing issue related to this on GitHub, although it has not received significant attention: