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

问题描述

我的代码如下所示,并且在 telemetryData .get(cid) 下,我不断收到带有红线的“对象可能未定义”错误。不知道如何解决这个问题?谢谢!

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) 分配给一个值,然后检查它是否未定义(或无效或虚假)。 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;
    }
})