cannot solve ts error: object is possibly undefined error
cannot solve ts error: object is possibly undefined error
我的代码如下所示,我在 telemetryData .get(cid) 下不断收到带有红线的 'object is possibly 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)
赋值给一个值,然后检查它是否未定义(或无效或错误)。 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;
}
})
我的代码如下所示,我在 telemetryData .get(cid) 下不断收到带有红线的 'object is possibly 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)
赋值给一个值,然后检查它是否未定义(或无效或错误)。 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;
}
})