In TypeScript 3.7.2 I can use Optional Chaining.
requests?.requestsCount
Can you explain how it works?
// before
requests ? req
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? Because the name undefined is not reserved in javascript and can be (in older engines at least) overwritten to something else. void 0 or void whatever is a bullet-proof way to obtain the undefined value.
Why the temporary variable _a and not just 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. In the same vein, for longer chains like x?.y?.z... the compiler will allocate more temporary variables _b, _c etc.
I hope this answers your questions.