You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript可选链触发ESLint错误,如何合规修复?

修复ESLint no-unsafe-optional-chaining规则错误

问题1:解构可选链返回的undefined触发TypeError

错误原因

当Employee为null或undefined时,Employee?.addresses会返回undefined,直接对undefined执行对象解构操作会抛出TypeError,这属于ESLint规则禁止的不安全用法。

修复方案

给解构操作设置默认空对象兜底,确保解构始终有合法的对象可访问。优先使用空值合并运算符??(仅当左侧为null/undefined时才返回右侧值,比||更严谨):

const { homeAddress, officeAddress } = Employee?.addresses ?? {};

如果环境不支持??,也可以用逻辑或||替代:

const { homeAddress, officeAddress } = Employee?.addresses || {};

问题2:可选链返回undefined导致算术运算得到NaN

错误原因

若homeAddress或officeAddress为null/undefined,homeAddress?.length会返回undefined,与数字相加后结果会变成NaN,不符合规则对安全运算的要求。

修复方案

使用空值合并运算符??将undefined替换为0,保证参与运算的都是合法数字:

const AddressesCount = (homeAddress?.length ?? 0) + (officeAddress?.length ?? 0);

内容的提问来源于stack exchange,提问作者V2rson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:22:05