My code is something like below and I keep getting 'object is possibly undefined' error with red lines under telemetryData .get(cid). Not sure how to solve this issue? Thanks!
const updateLoadedCount = mutatorAction('updateLoadedCount', (cid: string) => {
const telemetryData = getTelemetryStore()?.telemetryData;
if (telemetryData?.has(cid)) {
if (telemetryData .get(cid) !== undefined) {
telemetryData .get(cid).imageLoaded =
telemetryData .get(cid).imageLoaded + 1;
}
}
})
You need to assign telemtryData.get(cid)
to a value and then check if it is undefined (or nullish, or falsey). TypeScript isn't going to know that some condition isn't going to change the result of telemtryData.get(cid)
the next time it is called.
const updateLoadedCount = mutatorAction('updateLoadedCount', (cid: string) => {
const telemetryData = getTelemetryStore()?.telemetryData;
const cidValue = telemetryData?.get(cid);
if (cidValue !== undefined) {
cidValue.imageLoaded += 1;
}
})