Unions of TypedDicts
At runtime TypedDicts are only plain dictionaries. I.e. it is not possible to distinguish a Union of TypedDicts with isinstance. If you want to distinguish Unions of TypedDicts, it is recommended to use the tagged union pattern:
from typing import Literal, TypedDict, Union
class A(TypedDict):
"A"]
tag: Literal[int
a:
class B(TypedDict):
"B"]
tag: Literal[str
b:
= Union[A, B]
TDs
def match(t: TDs) -> None:
if t["tag"] == "A":
print(t["a"])
else:
print(t["b"])
In existing code bases which use a lot of dicts a Union of TypedDicts may appear when types are introduced. The question is then if it is possible to introduce an additional field or if you have to silence the error temporarily until the code is cleaned up.