Skip to content

Fix false positive "Expected TypedDict key to be string literal" for Union[TypedDict, dict[K, V]]#21511

Merged
ilevkivskyi merged 1 commit into
python:masterfrom
JiwaniZakir:fix/issue-21510
May 19, 2026
Merged

Fix false positive "Expected TypedDict key to be string literal" for Union[TypedDict, dict[K, V]]#21511
ilevkivskyi merged 1 commit into
python:masterfrom
JiwaniZakir:fix/issue-21510

Conversation

@JiwaniZakir
Copy link
Copy Markdown
Contributor

When a variable is typed as Union[TypedDict, dict[int, float]], mypy incorrectly
raised Expected TypedDict key to be string literal when assigning a dict literal
with non-string keys like {1: 5.2}. The plain dict[int, float] alternative makes
the assignment valid, so this was a false positive.

The root cause was that match_typeddict_call_with_dict, which is used as a probe to
check whether a dict literal could match a TypedDict, was emitting errors from
validate_typeddict_kwargs during the matching phase rather than silently returning
False. Wrapping the call in filter_errors() suppresses those spurious diagnostics.

Fixes #21510

…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 python#21510
@github-actions
Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Copy link
Copy Markdown
Member

@ilevkivskyi ilevkivskyi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, this one looks reasonable.

@ilevkivskyi ilevkivskyi merged commit d23f5f0 into python:master May 19, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

error: Expected TypedDict key to be string literal for Union of TypedDict and dict

2 participants