无法解决ts错误:对象可能是未定义的错误



我的代码如下,我在telemetryData.get(cid(下不断收到带有红线的"object is possible undefined"错误。不知道如何解决这个问题?谢谢

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;
}
}
})

您需要将telemtryData.get(cid)分配给一个值,然后检查它是否未定义(或为null或false(。TypeScript不会知道某个条件在下次调用telemtryData.get(cid)时不会更改其结果。

const updateLoadedCount = mutatorAction('updateLoadedCount', (cid: string) => {
const telemetryData = getTelemetryStore()?.telemetryData;
const cidValue = telemetryData?.get(cid);
if (cidValue !== undefined) {
cidValue.imageLoaded += 1;
}
})

最新更新