Skip to content

Commit 624e52e

Browse files
committed
Improve instanceof for structurally identical types
1 parent 8ea90ab commit 624e52e

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/compiler/checker.ts

Lines changed: 5 additions & 1 deletion
Original file line numberOriginal file lineDiff line numberDiff line change
@@ -8569,8 +8569,12 @@ namespace ts {
8569
}
8569
}
8570

8570

8571
function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean) {
8571
function getNarrowedType(type: Type, candidate: Type, assumeTrue: boolean) {
8572+
// In the false branch we keep types that aren't subtypes of the candidate type and we keep structurally
8573+
// identical types except for the current type itself. The latter rule means that given two structurally
8574+
// identical classes A and B and a variable x of type A, in the false branch of an 'x instanceof B' type
8575+
// guard x keeps type A and is not narrowed to type never.
8572
if (!assumeTrue) {
8576
if (!assumeTrue) {
8573-
return filterType(type, t => !isTypeSubtypeOf(t, candidate));
8577+
return filterType(type, t => !isTypeSubtypeOf(t, candidate) || isTypeIdenticalTo(t, candidate) && t !== candidate);
8574
}
8578
}
8575
// If the current type is a union type, remove all constituents that aren't assignable to
8579
// If the current type is a union type, remove all constituents that aren't assignable to
8576
// the candidate type. If one or more constituents remain, return a union of those.
8580
// the candidate type. If one or more constituents remain, return a union of those.

0 commit comments

Comments
 (0)