如何避免数组提取失败?处理ExtendedMap.get返回undefined或null的安全方案
如何安全处理ExtendedMap.get()返回undefined/null的场景?
你提到的...(this.state.drawSourceIdRegistryPolygons.get(registryId) || [])完全是可行的解决方案,而且是处理这类空值场景的常用手法,能有效保障代码安全。
为什么这个写法有效?
当get(registryId)返回undefined或null时,逻辑或运算符||会自动返回右侧的空数组[]。扩展运算符...作用在空数组上不会产生任何元素,相当于直接忽略了这个可能为空的部分,完美避免了因为尝试扩展undefined/null而抛出的类型错误。
更严谨的替代方案(TS 3.7+)
如果你的业务场景中,get()有可能返回其他假值(比如空数组[]本身),可以用**空值合并运算符??**替代||,它只会在值为null或undefined时才返回默认值,比||更精准:
...(this.state.drawSourceIdRegistryPolygons.get(registryId) ?? [])
不过如果你的场景里get()只会返回number[]、undefined或null,两种写法效果完全一致。
简化的TS复现代码
下面是一个可直接运行的TypeScript示例,模拟你的场景:
// 模拟自定义的ExtendedMap类 class ExtendedMap<K, V> extends Map<K, V> {} // 模拟状态对象 const state = { drawSourceIdRegistryPolygons: new ExtendedMap<number, number[]>() }; const targetRegistryId = 123; const newPolygonIds = [456, 789]; // 安全合并数组的写法 state.drawSourceIdRegistryPolygons.set(targetRegistryId, [ ...(state.drawSourceIdRegistryPolygons.get(targetRegistryId) || []), ...newPolygonIds, ]); console.log(state.drawSourceIdRegistryPolygons.get(targetRegistryId)); // 第一次执行输出: [456, 789] // 再次添加新元素 state.drawSourceIdRegistryPolygons.set(targetRegistryId, [ ...(state.drawSourceIdRegistryPolygons.get(targetRegistryId) ?? []), ...[101112], ]); console.log(state.drawSourceIdRegistryPolygons.get(targetRegistryId)); // 第二次执行输出: [456, 789, 101112]
这个示例里,第一次调用set时,get()返回undefined,|| []提供了空数组兜底;第二次调用时,get()已经能拿到之前存储的数组,所以会顺利合并新元素。
内容的提问来源于stack exchange,提问作者user15361861
相关产品推荐
相关产品推荐

