Can you explain TypeScript 3.7 Optional Chaining?

后端 未结 1 983
借酒劲吻你
借酒劲吻你 2021-01-28 17:29

In TypeScript 3.7.2 I can use Optional Chaining.

requests?.requestsCount

Can you explain how it works?

// before
requests ? req         


        
1条回答
  •  清酒与你
    2021-01-28 17:52

    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.

    0 讨论(0)
提交回复
热议问题