diff --git a/pyrefly/lib/alt/expr.rs b/pyrefly/lib/alt/expr.rs index a0d1c7af73..9c98a7fe41 100644 --- a/pyrefly/lib/alt/expr.rs +++ b/pyrefly/lib/alt/expr.rs @@ -2336,15 +2336,19 @@ impl<'a, Ans: LookupAnswer> AnswersSolver<'a, Ans> { Some(&|| ErrorContext::Index(self.for_display(base.clone()))), ), Type::Quantified(ref q) if q.is_type_var() && q.restriction().is_restricted() => { - self.call_method_or_error( - &base, - &dunder::GETITEM, - range, - &[CallArg::expr(slice)], - &[], - errors, - Some(&|| ErrorContext::Index(self.for_display(base.clone()))), - ) + match q.restriction() { + Restriction::Bound(bound) => { + self.subscript_infer_for_type(bound, slice, range, errors) + } + Restriction::Constraints(constraints) => { + self.unions(constraints.map(|constraint| { + self.subscript_infer_for_type(constraint, slice, range, errors) + })) + } + Restriction::Unrestricted => { + unreachable!("restricted TypeVar cannot be unrestricted") + } + } } Type::TypedDict(typed_dict) => { let key_ty = self.expr_infer(slice, errors); diff --git a/pyrefly/lib/test/typed_dict.rs b/pyrefly/lib/test/typed_dict.rs index 43acf2aa4d..28313d827a 100644 --- a/pyrefly/lib/test/typed_dict.rs +++ b/pyrefly/lib/test/typed_dict.rs @@ -2536,3 +2536,38 @@ def f(x: str) -> TD[int] | TD[str]: return TD(value=x) "#, ); + +testcase!( + test_constrained_type_var_typed_dict_index, + r#" +from typing import Generic, TypedDict, TypeVar, assert_type + +class DeviceInfo(TypedDict): + name: str + address: str + rssi: int + +class ExtendedDeviceInfo(TypedDict): + name: str + address: str + rssi: int + manufacturer: str + +NAME = "name" +ADDRESS = "address" + +T = TypeVar("T", DeviceInfo, ExtendedDeviceInfo) + +class DeviceIndex(Generic[T]): + def __init__(self) -> None: + self.by_name: dict[str, list[T]] = {} + + def add(self, device: T) -> None: + name = device[NAME] + assert_type(name, str) + self.by_name.setdefault(name, []).append(device) + + def lookup(self, device: T) -> str: + return device[ADDRESS] +"#, +);