简体   繁体   English

在 javascript 中使用可选链接的铸造类型

[英]casting type using optional chaining in javascript

we can safety access to deeper level of object by doing我们可以通过做安全访问更深层次的 object

data?.user?.age

but can I do casting at the same line?但我可以在同一行进行铸造吗?

const ageInNumber = +data?.user?.age!

typescript doesn't throw error but I'm not sure it won't give me trouble. typescript 不会抛出错误,但我不确定它不会给我带来麻烦。

The optional chaining operator ( ?. ) returns undefined if its first operand is null or undefined .如果其第一个操作数是nullundefined ,则可选链接运算符 ( ?. ) 返回undefined

Casting undefined to a number won't raise any exceptions, just silently returns NaN .undefined转换为数字不会引发任何异常,只是默默地返回NaN If that's acceptable to you, then that part is OK.如果这对你来说是可以接受的,那么那部分就可以了。

However, the non-null assertion ( ! ) is problematic.但是,非空断言 ( ! ) 是有问题的。 According to this GitHub issue , TS evaluates a?.b!根据这个 GitHub 问题,TS 评估a?.b! as (a?.b)!作为(a?.b)! , asserting the entire chain, not just the .b part. ,断言整个链,而不仅仅是.b部分。 So:所以:

  • If none of the parts may ever be nullish , then the ?.如果没有一个部分可能是无效的,那么?. 's are superfluous , and you should replace them with regular property access ( . ) to increase clarity.是多余的,您应该将它们替换为常规的属性访问 ( . ) 以增加清晰度。

  • If any of the parts can be nullish , it will short-circuit with undefined , and the non-null assertion is violated .如果任何部分可以为 nullish ,它将与undefined短路,并且违反了非 null 断言 If that's the case, you should remove the assertion.如果是这种情况,您应该删除断言。

    However, if the last part (ie the age property of data.user ) can be null (not undefined ), then the entire chain returns null , which casts to 0 , therefore is indistinguishable from a real zero received in the data.但是,如果最后一部分(即data.userage属性)可以是null (不是undefined ),则整个链返回null ,它强制转换为0 ,因此与数据中接收到的实际零无法区分。 To make it NaN too (or set a default value), you can use the nullish-coalescing operator ( ?? ):要使其也为NaN (或设置默认值),您可以使用 nullish-coalescing 运算符 ( ?? ):

     const ageInNumber = +(data?.user?.age?? NaN)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM