在JavaScript中的可选链操作导致ESLint错误。

huangapple go评论125阅读模式
英文:

optional chaining in javascript causing error in eslint

问题

错误:在可选链上的不安全使用。如果它与 'undefined' 短路,评估将抛出 TypeError no-unsafe-optional-chaining

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

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

英文:

i tried to use optional chaining in javascript but my eslint rules causing error .

Error : Unsafe usage of optional chaining. If it short-circuits with 'undefined' the evaluation will throw TypeError no-unsafe-optional-chaining

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

Error : Unsafe arithmetic operation on optional chaining. It can result in NaN
no-unsafe-optional-chaining

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

how can I fix this issue ? I do not want to violate the rule

答案1

得分: 5

有多种方法可以解决这个问题,或者你可以使用 /* eslint-disable-next-line no-unsafe-optional-chaining */。我不建议这样做,但它可以解决错误。

在我看来,最好的解决方法是使用 const { homeAddress, officeAddress } = Employee?.addressess || {};。你还可以尝试 const { addresses: { homeAddress, officeAddress } } = Employee;

英文:

There are multiple ways to fix this, or you can use /* eslint-disable-next-line no-unsafe-optional-chaining */. Which I would not advise but it will fix the errors.
The best way to fix this in my opinion is by using const { homeAddress, officeAddress } = Employee?.addressess || {};. What you can also try is const { addresses: { homeAddress, officeAddress } } = Employee;

答案2

得分: 3

对于第二个问题:

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

for the second issue:

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

答案3

得分: 1

提供默认值:

const { addresses: { homeAddress, officeAddress} = { homeAddress: '', officeAddress: '' } } = Employee

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

这样,你确保了键的存在,并且会得到一个默认值(在这种情况下是空字符串),而你的代码不会出错。

英文:

Provide a default value

const { addresses: { homeAddress, officeAddress} = { homeAddress: &#39;&#39;, officeAddress: &#39;&#39;} } = Employee

console.log(homeAddress) // &lt;empty string&gt;
console.log(officeAddress) // &lt;empty string&gt;

This way you're making sure keys exists and you'll be getting a default value(empty string in this case) and your code doesn't breaks.

huangapple
  • 本文由 发表于 2023年3月7日 15:27:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定