polRk
polRk

Reputation: 219

Can you explain TypeScript 3.7 Optional Chaining?

In TypeScript 3.7.2 I can use Optional Chaining.

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 ? In release docs it should be undefined.

let x = (foo === null || foo === undefined) ? undefined : foo.bar.baz();

May I use this syntactic sugar safely?

Upvotes: 0

Views: 94

Answers (1)

georg
georg

Reputation: 214949

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.

Upvotes: 4

Related Questions