最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - optional chaining in javascript causing error in eslint - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Mar 7, 2023 at 7:27 V2rsonV2rson 3471 gold badge3 silver badges11 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

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;

for the second issue:

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

Provide a default value

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

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

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.

发布评论

评论列表(0)

  1. 暂无评论