JavaScript 中的可选链在 eslint 中导致错误。

3
我尝试在JavaScript中使用可选链式调用,但我的ESLint规则导致错误。
错误:不安全的可选链使用。如果它通过“undefined”短路,则评估将抛出TypeError no-unsafe-optional-chaining。
const { homeAddress, officeAddress} = Employee?.addresses;

错误:可选链上的不安全算术操作。可能导致 NaN no-unsafe-optional-chaining

const AddressesCount = homeAddress?.length + officeAddress?.length 

我该如何解决这个问题?我不想违反规定。

3个回答

6

有多种方法可以解决这个问题,或者您可以使用/* eslint-disable-next-line no-unsafe-optional-chaining */。我不建议使用它,但它会修复错误。 在我看来,最好的解决方法是使用const { homeAddress, officeAddress } = Employee?.addressess || {};。您还可以尝试const { addresses: { homeAddress, officeAddress } } = Employee;


2
如果Employee为空或未定义,Employee.addresses || {}会抛出异常... - derpirscher
那么我该如何解决这个问题呢?@derpirscher - V2rson
3
就像你在原始代码中所做的那样:Employee?.addresses,但你需要回退到一个空对象,这样解构就不会在 null 或 undefined 上抛出错误。因此,使用 Employee?.addresses || {} - derpirscher
您是绝对正确的,我会编辑我的答案。 - Lars Vonk

3

关于第二个问题:

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

1
提供一个默认值。
const { addresses: { homeAddress, officeAddress} = { homeAddress: '', officeAddress: ''} } = Employee

console.log(homeAddress) // <empty string>
console.log(officeAddress) // <empty string>

这样做可以确保键存在,并获得默认值(在此情况下为空字符串),从而避免代码崩溃。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接