Merging two TypedDict
into one dict[K, V]
#1275
-
Hi, If I use unpacking, both type checkers accept the code. from typing import TypedDict
from typing_extensions import reveal_type
class A(TypedDict):
x: str
z: str
class B(TypedDict):
x: str
y: str
a: A = {'x': 'a', 'z': 'a'}
b: B = {'x': 'b', 'y': 'b'}
c = a | b # <-- error: Operator "|" not supported for types "A" and "B"
reveal_type(c) # pyright: unknown, mypy: TypedDict('typed_dict_merge.A', {'x': builtins.str, 'z': builtins.str})
d = {**a, **b}
reveal_type(d) # pyright: dict[str, str], mypy: builtins.dict[builtins.str, builtins.object]
print(c == d) # prints True at runtime Is there a way to annotate the code in a way to use the c: dict[str, str] = a | b # error still persists Creating a compatible class C(A, B, TypedDict):
pass
c: C = a | b # same as before
e: C = {'x': 'b', 'z': 'a', 'y': 'b'} # ok
d: C = {**a, **b} # ok in pyright, error in mypy: Expected TypedDict key to be string literal
reveal_type(d) # revealed as C Context Version |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think the ideal solution here is just to wait for Intersection to be finished (see #213) |
Beta Was this translation helpful? Give feedback.
I think the ideal solution here is just to wait for Intersection to be finished (see #213)