Skip to content

Commit 6fbd2a5

Browse files
committed
Reset narrowing of 'x.y' only when 'x' has a narrowable type
1 parent eadf44d commit 6fbd2a5

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/compiler/checker.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14340,6 +14340,11 @@ namespace ts {
1434014340
return false;
1434114341
}
1434214342

14343+
function hasNarrowableDeclaredType(expr: Node) {
14344+
const type = getDeclaredTypeOfReference(expr);
14345+
return !!(type && type.flags & TypeFlags.Union);
14346+
}
14347+
1434314348
function findDiscriminantProperties(sourceProperties: Symbol[], target: Type): Symbol[] | undefined {
1434414349
let result: Symbol[] | undefined;
1434514350
for (const sourceProperty of sourceProperties) {
@@ -15373,9 +15378,9 @@ namespace ts {
1537315378
// We have '==', '!=', '====', or !==' operator with 'typeof xxx' and string literal operands
1537415379
const target = getReferenceCandidate(typeOfExpr.expression);
1537515380
if (!isMatchingReference(reference, target)) {
15376-
// For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the
15377-
// narrowed type of 'y' to its declared type.
15378-
if (containsMatchingReference(reference, target)) {
15381+
// For a reference of the form 'x.y', where 'x' has a narrowable declared type, a
15382+
// 'typeof x === ...' type guard resets the narrowed type of 'y' to its declared type.
15383+
if (containsMatchingReference(reference, target) && hasNarrowableDeclaredType(target)) {
1537915384
return declaredType;
1538015385
}
1538115386
return type;
@@ -15516,9 +15521,9 @@ namespace ts {
1551615521
function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type {
1551715522
const left = getReferenceCandidate(expr.left);
1551815523
if (!isMatchingReference(reference, left)) {
15519-
// For a reference of the form 'x.y', an 'x instanceof T' type guard resets the
15520-
// narrowed type of 'y' to its declared type.
15521-
if (containsMatchingReference(reference, left)) {
15524+
// For a reference of the form 'x.y', where 'x' has a narrowable declared type, an
15525+
// 'x instanceof T' type guard resets the narrowed type of 'y' to its declared type.
15526+
if (containsMatchingReference(reference, left) && hasNarrowableDeclaredType(left)) {
1552215527
return declaredType;
1552315528
}
1552415529
return type;

0 commit comments

Comments
 (0)