Is there a method in TypeScript to restrict an object property, accessed dynamically using a variable, from containing undefined
values?
The code snippet provided on the TS playground showcases this issue:
interface Dict {
[k: string]: {
prop?: number;
};
}
const d: Dict = {};
let a = "item";
const b = a;
const c = "item";
if (d[a].prop) {
d[a].prop++ // Nope
}
if (d[b].prop) {
d[b].prop++ // Neither
}
if (d[c].prop) {
d[c].prop++ // OK
}
This demonstrates how TypeScript throws errors when attempting to exclude undefined
values while accessing dictionary/object values using variables or their copies. The scenario only works when constants are used with literal definitions.
What is the solution to overcome this behavior?