Skip to content

Commit 5ab8bd8

Browse files
Try to find object/intersection types with the most overlap when failing assignability against unions.
1 parent 2b888c3 commit 5ab8bd8

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/compiler/checker.ts

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11472,7 +11472,8 @@ namespace ts {
1147211472
findMatchingDiscriminantType(source, target) ||
1147311473
findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
1147411474
findBestTypeForObjectLiteral(source, target) ||
11475-
findBestTypeForInvokable(source, target);
11475+
findBestTypeForInvokable(source, target) ||
11476+
findMostOverlappyType(source, target);
1147611477

1147711478
isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
1147811479
}
@@ -11512,6 +11513,32 @@ namespace ts {
1151211513
}
1151311514
}
1151411515

11516+
function findMostOverlappyType(source: Type, unionTarget: UnionOrIntersectionType) {
11517+
if (!(source.flags & (TypeFlags.Object | TypeFlags.Intersection))) {
11518+
return undefined;
11519+
}
11520+
const sourceProperties = getPropertiesOfType(source);
11521+
let bestType;
11522+
let count = -1;
11523+
for (const target of unionTarget.types) {
11524+
if (!(target.flags & (TypeFlags.Object | TypeFlags.Intersection))) {
11525+
continue;
11526+
}
11527+
11528+
let currentCount = 0;
11529+
for (const prop of sourceProperties) {
11530+
if (getPropertyOfType(target, prop.escapedName)) {
11531+
currentCount++;
11532+
}
11533+
}
11534+
if (currentCount >= count) {
11535+
count = currentCount;
11536+
bestType = target;
11537+
}
11538+
}
11539+
return bestType;
11540+
}
11541+
1151511542
// Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
1151611543
function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) {
1151711544
let match: Type | undefined;

0 commit comments

Comments
 (0)