英文:
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: '', 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论