Skip to content

Commit 9cbde46

Browse files
Try to change some logic for contextual narrowing for any instantiable type to empty objects.
1 parent 68cc758 commit 9cbde46

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/compiler/checker.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25317,7 +25317,7 @@ namespace ts {
2531725317
return !!(type.flags & TypeFlags.Instantiable && !maybeTypeOfKind(getBaseConstraintOrType(type), TypeFlags.Nullable));
2531825318
}
2531925319

25320-
function hasContextualTypeWithNoGenericTypes(node: Node, checkMode: CheckMode | undefined) {
25320+
function tryGetContextualTypeWithNoGenericTypes(node: Node, checkMode: CheckMode | undefined) {
2532125321
// Computing the contextual type for a child of a JSX element involves resolving the type of the
2532225322
// element's tag name, so we exclude that here to avoid circularities.
2532325323
// If check mode has `CheckMode.RestBindingElement`, we skip binding pattern contextual types,
@@ -25327,7 +25327,7 @@ namespace ts {
2532725327
(checkMode && checkMode & CheckMode.RestBindingElement ?
2532825328
getContextualType(node, ContextFlags.SkipBindingPatterns)
2532925329
: getContextualType(node));
25330-
return contextualType && !isGenericType(contextualType);
25330+
return contextualType && !isGenericType(contextualType) ? contextualType : undefined;
2533125331
}
2533225332

2533325333
function getNarrowableTypeForReference(type: Type, reference: Node, checkMode?: CheckMode) {
@@ -25338,9 +25338,13 @@ namespace ts {
2533825338
// control flow analysis an opportunity to narrow it further. For example, for a reference of a type
2533925339
// parameter type 'T extends string | undefined' with a contextual type 'string', we substitute
2534025340
// 'string | undefined' to give control flow analysis the opportunity to narrow to type 'string'.
25341+
let contextualType: Type | undefined;
2534125342
const substituteConstraints = !(checkMode && checkMode & CheckMode.Inferential) &&
25342-
someType(type, isGenericTypeWithUnionConstraint) &&
25343-
(isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode));
25343+
(isConstraintPosition(type, reference) || (contextualType = tryGetContextualTypeWithNoGenericTypes(reference, checkMode))) &&
25344+
(
25345+
someType(type, isGenericTypeWithUnionConstraint) ||
25346+
((type.flags & TypeFlags.Instantiable) && contextualType && isEmptyObjectType(contextualType))
25347+
);
2534425348
return substituteConstraints ? mapType(type, t => t.flags & TypeFlags.Instantiable ? getBaseConstraintOrType(t) : t) : type;
2534525349
}
2534625350

0 commit comments

Comments
 (0)