diff --git a/mypy/semanal_typeddict.py b/mypy/semanal_typeddict.py index 5104d31f5c266..a013cc040e895 100644 --- a/mypy/semanal_typeddict.py +++ b/mypy/semanal_typeddict.py @@ -394,6 +394,17 @@ def check_typeddict( types = [ # unwrap Required[T] to just T t.item if isinstance(t, RequiredType) else t for t in types ] + + # Perform various validations after unwrapping. + for t in types: + check_for_explicit_any( + t, self.options, self.api.is_typeshed_stub_file, self.msg, context=call + ) + if self.options.disallow_any_unimported: + for t in types: + if has_any_from_unimported_type(t): + self.msg.unimported_type_becomes_any("Type of a TypedDict key", t, call) + existing_info = None if isinstance(node.analyzed, TypedDictExpr): existing_info = node.analyzed.info @@ -451,15 +462,6 @@ def parse_typeddict_args( # One of the types is not ready, defer. return None items, types, ok = res - for t in types: - check_for_explicit_any( - t, self.options, self.api.is_typeshed_stub_file, self.msg, context=call - ) - - if self.options.disallow_any_unimported: - for t in types: - if has_any_from_unimported_type(t): - self.msg.unimported_type_becomes_any("Type of a TypedDict key", t, dictexpr) assert total is not None return args[0].value, items, types, total, tvar_defs, ok diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index c1c791304a15a..c584906dd965f 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -3396,3 +3396,15 @@ reveal_type(b["a"]) # N: Revealed type is "Union[builtins.str, None]" reveal_type(b["g"]) # N: Revealed type is "Union[builtins.int, None]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] + +[case testNoCrashOnUnImportedAnyNotRequired] +# flags: --disallow-any-unimported +from typing import NotRequired, Required, TypedDict +from thismoduledoesntexist import T # type: ignore[import] + +B = TypedDict("B", { # E: Type of a TypedDict key becomes "Any" due to an unfollowed import + "T1": NotRequired[T], + "T2": Required[T], +}) +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi]