Include missing optional properties in contextually typed object literals #1774
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1723.
In #919 we tightened the subtyping rules to require optional properties to be present in subtypes. That's still the right thing to do, but it can have unintended consequences for overload resolution (which relies on subtyping) in combination with object literals.
With this PR, when an object literal is contextually typed by a type T, any optional properties in T that are omitted in the object literal are included in the resulting type, thus ensuring the resulting type is a subtype of T when all that was omitted was optional properties (whew!). For example
In the first call to foo above, contextual typing of the object literal adds the missing optional property. Thus, the argument expression becomes a subtype of Item, and the first overload is chosen (as one would expect).
This change does at times affect error reporting. For example
Here we'll now report
Depending on your point of view it may be surprising that the reported type includes an optional property that you didn't actually write (but which is there because of your context).