Skip to content

Commit eb1e7ec

Browse files
committed
Optimize T[K] where T has string index signature and no other members
1 parent 71f3e1f commit eb1e7ec

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/compiler/checker.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10145,6 +10145,11 @@ namespace ts {
1014510145
if (objectType === wildcardType || indexType === wildcardType) {
1014610146
return wildcardType;
1014710147
}
10148+
// If the object type has a string index signature and no other members we know that the result will
10149+
// always be the type of that index signature and we can simplify accordingly.
10150+
if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & TypeFlags.Nullable) && isTypeAssignableToKind(indexType, TypeFlags.String | TypeFlags.Number)) {
10151+
indexType = stringType;
10152+
}
1014810153
// If the index type is generic, or if the object type is generic and doesn't originate in an expression,
1014910154
// we are performing a higher-order index access where we cannot meaningfully access the properties of the
1015010155
// object type. Note that for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in
@@ -12022,6 +12027,12 @@ namespace ts {
1202212027
return !!(getObjectFlags(type) & ObjectFlags.Anonymous) && isEmptyObjectType(type);
1202312028
}
1202412029

12030+
function isStringIndexSignatureOnlyType(type: Type): boolean {
12031+
return type.flags & TypeFlags.Object && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, IndexKind.String) && !getIndexInfoOfType(type, IndexKind.Number) ||
12032+
type.flags & TypeFlags.UnionOrIntersection && every((<UnionOrIntersectionType>type).types, isStringIndexSignatureOnlyType) ||
12033+
false;
12034+
}
12035+
1202512036
function isEnumTypeRelatedTo(sourceSymbol: Symbol, targetSymbol: Symbol, errorReporter?: ErrorReporter) {
1202612037
if (sourceSymbol === targetSymbol) {
1202712038
return true;

0 commit comments

Comments
 (0)