Is the documentation of optional chaining wrong?

I just realized (here) that I had the wrong idea about one aspect of optional chaining's behavior, so I read about it in TSPL. And I think the documentation is wrong in at least two places.

Here's the third paragraph of the first sub-section about optional chaining:

Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.

The first sentence (and everything else before it) suggests that the second sentence is a specific example of a more general statement:

  • A property that normally returns a T will return a T? when accessed through optional chaining.

But this is only true for all non-optional T, ie the above statement is false, because of the special rule that says that when T == U? == Optional<U>, then T will not be "wrapped in an optional".

In order for the quoted paragraph to be correct, it would have to be changed into something like:

Specifically, the result of an optional chaining call is of the same type T as the expected return value, but wrapped in an optional except if T is statically known to be of type T == Optional<U>, in which case T is not wrapped in (one more) optional. A property that normally returns an Int will return an Int? when accessed through optional chaining, but a property that normally returns an Int?? will return an Int?? when accessed through optional chaining.

(But preferably much simpler, if possible without getting it wrong again.)


It's only way down towards the end of the very long documentation that the reader is introduced to the special rule, in a section called Linking Multiple Levels of Chaining:

You can link together multiple levels of optional chaining to drill down to properties, methods, and subscripts deeper within a model. However, multiple levels of optional chaining do not add more levels of optionality to the returned value.

To put it another way:

  • If the type you are trying to retrieve is not optional, it will become optional because of the optional chaining.
  • If the type you are trying to retrieve is already optional, it will not become more optional because of the chaining.

These two bullet points finally mentions the special rule, but I do not see how this has anything at all to do with "multiple levels of optional chaining". It only has to do with the "type you are trying to retrieve" and whether it is statically known to already be or not be optional. This is as true for an expression with a single ?. as it is for an expression with multiple ?.s linked together.


Is it me or the documentation that is wrong?

2 Likes
Terms of Service

Privacy Policy

Cookie Policy