10

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

3 Answers 3

12

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;

Sign up to request clarification or add additional context in comments.

4 Comments

Employee.addresses || {} will throw an exception if Employee is null or undefined ...
so how can i overcome that issue ? @derpirscher
Like you did in your original code: Employee?.addresses but you need the fallback to an empty object, so that the deconstruction won't throw an error on null or undefined. So Employee?.addresses || {}
You are absolutely right i will edit my nswer
3

for the second issue:

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

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.