tc39 / proposal-optional-chaining

https://tc39.github.io/proposal-optional-chaining/
4.94k stars 75 forks source link

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

Closed dantheobserver closed 3 years ago

dantheobserver commented 3 years ago

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.

ljharb commented 3 years ago

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.

claudepache commented 3 years ago

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.

dantheobserver commented 3 years ago

@claudepache that note clarifies it clearly

chpio commented 3 years ago

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