tomitrescak
tomitrescak

Reputation: 1110

Mypy loses type of the TypedDict when unpacked

I have the following code when trying to spread the dictionary from typing import TypedDict

class MyDict(TypedDict):
    foo: int

def test(inp: MyDict):
    m: MyDict = inp # OK
    n: MyDict = {**inp} # <-- ERROR

I receive an error Expression of type "dict[str, object]" cannot be assigned to declared type

Any idea how can I preserve the type after spread?

Upvotes: 1

Views: 873

Answers (1)

Paweł Rubin
Paweł Rubin

Reputation: 3350

Currently, neither mypy nor pyright is smart enough to infer the type of an unpacked dict. See https://github.com/python/mypy/issues/4122.

As a workaround use typing.cast:

from typing import cast, TypedDict


class MyDict(TypedDict):
    foo: int


def test(inp: MyDict):
    m: MyDict = inp # OK
    n: MyDict = cast(MyDict, {**inp}) # OK

Upvotes: 2

Related Questions