String literal apparent types with specific member types #19846
Closed
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.
As mentioned in #19837, calculating the apparent type of union members correctly exposed some undesired behavior with respect to the contextual type produced by the union of a string literal type and an array. The root cause is the index signature in the global string type; so another way to fix the issue is to give string literal type more specific apparent types than the global string type. In this PR, I create a cached apparent type (similar to what we do for intersections) for string literal types which has exact types for the 0 through N properties of the string, based on the text of the literal, and then a more specific index signature based on those types. This also has the nice sideffect of giving you stronger types for
("foo")[2]
("o"
) orkeyof "someLiteral"
(all the names onString
plus"0"
- N; up to the length of the literal.). Only doing this for the apparent type saves us from comparing these properties during relationships, while still giving us the benefits of stronger property types than the indexer on the original apparent type gives.Fixes #19837