Skip to content

Commit e7668ae

Browse files
committed
Added support for a TypeGuard function where the first argument is a TypeVar. In this case, the resulting (narrowed) type should be a conditional type that references the TypeVar.
1 parent 98e2134 commit e7668ae

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎packages/pyright-internal/src/analyzer/typeEvaluator.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10992,10 +10992,31 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions
1099210992
specializedReturnType.typeArguments.length > 0
1099310993
) {
1099410994
if (boolClassType && isInstantiableClass(boolClassType)) {
10995+
let typeGuardType = specializedReturnType.typeArguments[0];
10996+
10997+
// If the first argument is a simple (non-constrained) TypeVar,
10998+
// associate that TypeVar with the resulting TypeGuard type.
10999+
if (argResults.length > 0) {
11000+
const arg0Type = argResults[0].argType;
11001+
if (
11002+
isTypeVar(arg0Type) &&
11003+
!arg0Type.details.isParamSpec &&
11004+
arg0Type.details.constraints.length === 0
11005+
) {
11006+
typeGuardType = addConditionToType(typeGuardType, [
11007+
{
11008+
typeVarName: TypeVarType.getNameWithScope(arg0Type),
11009+
constraintIndex: 0,
11010+
isConstrainedTypeVar: false,
11011+
},
11012+
]) as ClassType;
11013+
}
11014+
}
11015+
1099511016
specializedReturnType = ClassType.cloneAsInstance(
1099611017
ClassType.cloneForTypeGuard(
1099711018
boolClassType,
10998-
specializedReturnType.typeArguments[0],
11019+
typeGuardType,
1099911020
ClassType.isBuiltIn(specializedReturnType, 'StrictTypeGuard')
1100011021
)
1100111022
);

‎packages/pyright-internal/src/tests/samples/typeGuard1.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,14 @@ def func3(x: Any):
9090
i = IsInt()
9191
if i(x):
9292
reveal_type(x, expected_text="int")
93+
94+
95+
def is_int(obj: type) -> TypeGuard[type[int]]:
96+
...
97+
98+
99+
def func4(typ: type[_T]) -> _T:
100+
if not is_int(typ):
101+
raise Exception("Unsupported type")
102+
103+
return typ()

0 commit comments

Comments
 (0)