Fix getConstraintOfIndexedAccess #17870
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.
Fixes #17069
Fixes #15371
T[K]
now correctly producesnumber
whenK extends string, T extends Record<K, number>
.T[K]
no longer allows any type to be assigned to it whenT extends object, K extends keyof T
.Previously both of these cases failed in
getConstraintOfIndexedAccessType
because both bases followedK
's base constraint tostring
and then incorrectly producedany
for types (likeobject
) with no string index signature. In (1), this produced an error in checkBinaryLikeExpression. In (2), this failed to produce an error in
checkTypeRelatedTo`.The fix has some additional pieces.
In order to fix (1), not only does the index type parameter need to be kept around, the base constraint of
T extends Record<K, number>
needs to beRecord<K, number>
not{}
so thatRecord<K, number>[K]
producesnumber
. So I changedcomputeBaseConstraint
to only chaseT extends Record<K, number>
back toRecord<K, number>
, not all the way to{}
.In order to fix (2), any index type whose base constraint is string, whether it came from
keyof T
or not, is going to (incorrectly) produceany
when indexing a type that doesn't have a string index signature -- the test case specifically triesobject[string]
. So I added an early exit togetConstraintOfIndexedAccessType
that returnsundefined
in this case.