Skip to content

Commit

Permalink
Improved the "x is y" and "type(x) is y" type guards to better handle…
Browse files Browse the repository at this point in the history
… the case where `x` is a TypeVar. (#9437)
  • Loading branch information
erictraut authored Nov 10, 2024
1 parent 8e84c8c commit 0aa0c26
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions packages/pyright-internal/src/analyzer/typeGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2332,7 +2332,7 @@ function narrowTypeForTypeIs(evaluator: TypeEvaluator, type: Type, classType: Cl
if (isPositiveTest) {
if (matches) {
if (ClassType.isSameGenericClass(ClassType.cloneAsInstantiable(subtype), classType)) {
return addConditionToType(subtype, classType.props?.condition);
return addConditionToType(subtype, getTypeCondition(classType));
}

return addConditionToType(ClassType.cloneAsInstance(classType), subtype.props?.condition);
Expand All @@ -2354,7 +2354,9 @@ function narrowTypeForTypeIs(evaluator: TypeEvaluator, type: Type, classType: Cl
return subtype;
}
} else if (isAnyOrUnknown(subtype)) {
return isPositiveTest ? ClassType.cloneAsInstance(classType) : subtype;
return isPositiveTest
? ClassType.cloneAsInstance(addConditionToType(classType, getTypeCondition(subtype)))
: subtype;
}

return unexpandedSubtype;
Expand Down Expand Up @@ -2386,7 +2388,7 @@ function narrowTypeForClassComparison(
}

if (isAnyOrUnknown(concreteSubtype)) {
return classType;
return addConditionToType(classType, getTypeCondition(concreteSubtype));
}

if (isClass(concreteSubtype)) {
Expand All @@ -2405,7 +2407,7 @@ function narrowTypeForClassComparison(
}

if (isSuperType) {
return classType;
return addConditionToType(classType, getTypeCondition(concreteSubtype));
}

const isSubType = ClassType.isDerivedFrom(classType, concreteSubtype);
Expand Down

0 comments on commit 0aa0c26

Please sign in to comment.