Skip to content

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

@AllexVeldman

Description

@AllexVeldman

Bug Report

Error for a valid input to TypedDict | dict[int, float]

To Reproduce
https://mypy-play.net/?gist=3d0a2913c33c47b405cb297df1607e8f

from typing import TypedDict

class Foo(TypedDict):
    some: str
    name: str

type Bar = dict[int, float]

type Baz = Foo | Bar

baz: Baz = {"some": "foo", "name": "x"}  # OK
bar: Bar = {1: 5.2, 2: 7.4}  # OK

baz2: Baz = {1: 5.2} # error: Expected TypedDict key to be string literal  [misc]

Expected Behavior
I would expect baz2 to be valid

Actual Behavior

main.py:14: error: Expected TypedDict key to be string literal  [misc]
Found 1 error in 1 file (checked 1 source file)

When mis-typing the dict variant mypy does give an expected error:

baz3: Baz = {"1": 5.2} # error: Dict entry 0 has incompatible type "str": "float"; expected "int": "float"  [dict-item]

Your Environment

  • Mypy version used: 2.1.0

Original discussion: python/typing#2292

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions