From eda6b5ed229aeafa95bea759efb3c9876ee1be72 Mon Sep 17 00:00:00 2001 From: Claude Agent Date: Tue, 19 May 2026 16:03:56 +0000 Subject: [PATCH] Fix false positive "Expected TypedDict key to be string literal" for Union[TypedDict, dict[int, float]] When matching a dict literal against a union type containing both a TypedDict and a plain dict (e.g. `Union[Foo, dict[int, float]]`), `match_typeddict_call_with_dict` was emitting an error while probing whether the literal matched the TypedDict alternative. Suppress errors during matching so they are only reported during actual type checking. Fixes #21510 --- mypy/checkexpr.py | 3 ++- test-data/unit/check-typeddict.test | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index c968e5cc6923b..882d748afaead 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -932,7 +932,8 @@ def match_typeddict_call_with_dict( kwargs: list[tuple[Expression | None, Expression]], context: Context, ) -> bool: - result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee) + with self.msg.filter_errors(): + result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee) if result is not None: validated_kwargs, _ = result return callee.required_keys <= set(validated_kwargs.keys()) <= set(callee.items.keys()) diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index c74ae96d7763e..17a1fea22ef04 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -941,6 +941,18 @@ c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'} # E: Type of TypedDict is [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] +[case testTypedDictUnionWithNonTypedDictLiteralKey] +from typing import Union, TypedDict + +class Foo(TypedDict): + some: str + name: str + +baz: Union[Foo, dict[int, float]] = {1: 5.2} +baz2: Union[Foo, dict[int, float]] = {'some': 'x', 'name': 'y'} +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi] + -- Use dict literals [case testTypedDictDictLiterals]