tc39/proposal-optional-chaining

Inconsistencies (perhaps in documentation) with optional chaining function variant.

dantheobserver opened this issue ยท 4 comments

I have a small example highlighting an issue in understanding function variant of optional changing. As per the mdn documentation.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

let result = someInterface.customMethod?.();

In practice it's a bit confusing as shown here.

Screen Shot 2020-08-06 at 4 21 02 PM

I would expect that since chaining works by checking whether a previous element in the chain is undefined, as in the third example, it should work for the first. While I understand that there's a nuance to this example, I feel that optional chaining for most cases abstracts away the need to know the shape of what returns - as it does in the second example - but for a particular case, you have to handle it in a special way, that's not explicitly documented.

It intentionally should not work; every place in the chain that you want to be optional needs an explicit ?.. In other words, having testNullChain().test throw is intentional. Having testNullChain()?.test() throw when the value isn't a function is also intentional.

Thanks for pointing the issue (which is not an issue of optional chaining itself, but of its understanding). I have added a note in the MDN article in order to clarify the point.

@claudepache that note clarifies it clearly

chpio commented

@dantheobserver can you close this issue, as it's resolved now?