[英]Can you explain TypeScript 3.7 Optional Chaining?
In TypeScript 3.7.2 I can use Optional Chaining.在 TypeScript 3.7.2 中,我可以使用可选链接。
requests?.requestsCount
Can you explain how it works?你能解释一下它是如何工作的吗?
// before
requests ? requests.requestsCount : 0
// after
requests?.requestsCount || 0
I see compiled version of my code.我看到了我的代码的编译版本。
"use strict";
var _a;
return {
requests: ((_a = requests) === null || _a === void 0 ? void 0 : _a.requestsCount) || 0
};
Can you explain void 0
?你能解释一下
void 0
吗? In release docs it should be undefined.在发布文档中它应该是未定义的。
let x = (foo === null || foo === undefined) ? undefined : foo.bar.baz();
May I use this syntactic sugar safely?我可以安全地使用这种语法糖吗?
This compiled code这个编译的代码
var _a;
return {
requests: ((_a = requests) === null || _a === void 0 ? void 0 : _a.requestsCount)
};
does the following执行以下操作
_a = requests
if _a === null || _a === undefined
return {requests: undefined}
else
return {requests: _a.requestsCount}
Why void 0
and not just undefined
?为什么
void 0
而不仅仅是undefined
? Because the name undefined
is not reserved in javascript and can be (in older engines at least) overwritten to something else.因为
undefined
的名称在 javascript 中没有保留,并且可以(至少在旧引擎中)被覆盖为其他名称。 void 0
or void whatever
is a bullet-proof way to obtain the undefined
value. void 0
或void whatever
是获得undefined
值的防弹方法。
Why the temporary variable _a
and not just requests
?为什么临时变量
_a
而不仅仅是requests
? Because the compiler has to ensure that the argument is evaluated exactly once.因为编译器必须确保参数只计算一次。 Imagine:
想象:
someFunc()?.someProp
Without the temporary variable this would call someFunc
three times, which is not acceptable.如果没有临时变量,这将调用
someFunc
三次,这是不可接受的。 In the same vein, for longer chains like x?.y?.z...
the compiler will allocate more temporary variables _b
, _c
etc.同样,对于像
x?.y?.z...
这样的较长链,编译器将分配更多的临时变量_b
、 _c
等。
I hope this answers your questions.我希望这回答了你的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.