Reputation: 1110
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
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