Currently it is not valid to use a type-hint or bound to be any TypedDict
type, e.g.
TD = TypedDict("TD", a=int, b=str)
a_td_type: type[TypedDict] = TD # not OK; be any TypedDict type
a_td_form: TypeForm[TypedDict] = "TD" # not OK; TypeForm | ~TypeAlias with a bound
a_td: TypedDict = TD(a=1, b="2") # not OK; be any TypedDict
tdT = TypeVar("tdT", bound=TypedDict) # not OK
An example use case where this would be useful is if I want to access the dunder attributes, e.g.
def assure_keys[T: TypedDict](obj: dict, td: type[T]) -> TypeGuard[T]: # Not OK
return all(k in obj for k in td.__required_keys__)
if assure_keys(some_dict, TD): # accetable?
reveal_type(some_dict["a"]) # int
As an alternative a Protocol
could be defined with the attributes of TypedDict
, which however might not be backward/forward compatible and, IMO, is less intuitive to use as TypedDict
already exists.
Can’t we see TypedDict
itself as a usable type annotation that is similar to a Protocol?