In my code, I have defined an index-based type X
. However, when using a non-existing key, TypeScript does not accurately infer the result type as ValueType | undefined
.
Is there a solution to correct this issue?
type ValueType = {
foobar:string;
}
type X = {
indexbased: { [id: string]: ValueType}
}
const x : X = {indexbased: {}}
const id :string = "not-existing";
const indexvalue = x.indexbased[id];
// The inferred type is const indexvalue: ValueType
console.log(indexvalue.foobar);
// This results in an error: Cannot read properties of undefined (reading 'foobar')
--
Update
To address this problem, if I modify
type X = { indexbased: { [id: string]: ValueType|undefined} }
, then every entry needs to be checked while looping through them:
for (const [key, value] of Object.entries(x.indexbased)) {
console.log(`${key}: ${value.foobar}`);
}
This relates to the topic discussed at Why in TypeScript an array element accessed by index doesn't have "undefined" in its type?