Improved type inference for object literals #19513
Merged
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.
This PR improves type inference for multiple object literals occurring in the same context. When multiple object literal types contribute to a union type, we now normalize the object literal types such that all properties are present in each constituent of the union type. For example:
Previously we inferred type
{}
forobj
and the second line subsequently caused an error becauseobj
would appear to have no properties. That obviously wasn't ideal.The key insight behind this PR is that for object literal types we know that unspecified properties always have the value
undefined
. This is unlike regular object types where unspecified properties might have any value. Based on this fact we implement the following new rules:undefined
(normally such excess properties are permitted to have any type).undefined
to each constituent as appropriate such that all constituents have the same set of property names.An example of object literal normalization:
Nested object literals are likewise normalized:
Multiple object literal type inferences for the same type parameter are collapsed into a single normalized union type:
Fixes #19236.