Typescript 无法解决ts错误:对象可能是未定义的错误
我的代码如下所示,我一直在telemetryData.get(cid)下得到“对象可能未定义”错误,并带有红线。不知道如何解决这个问题?谢谢Typescript 无法解决ts错误:对象可能是未定义的错误,typescript,tslint,Typescript,Tslint,我的代码如下所示,我一直在telemetryData.get(cid)下得到“对象可能未定义”错误,并带有红线。不知道如何解决这个问题?谢谢 const updateLoadedCount = mutatorAction('updateLoadedCount', (cid: string) => { const telemetryData = getTelemetryStore()?.telemetryData; if (telemetryData?.has(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;
}
}
})
您需要将
teletrydata.get(cid)
分配给一个值,然后检查该值是否未定义(或为null,或为false)。TypeScript不会知道某些条件不会在下次调用时更改TeletryData.get(cid)
的结果
const updateLoadedCount = mutatorAction('updateLoadedCount', (cid: string) => {
const telemetryData = getTelemetryStore()?.telemetryData;
const cidValue = telemetryData?.get(cid);
if (cidValue !== undefined) {
cidValue.imageLoaded += 1;
}
})
非常感谢。这很有帮助!