What does `typing.TypedDict` add for code that works with plain dictionaries that have a fixed, known shape, such as parsed JSON?
Answer
`TypedDict` lets you declare that a plain `dict` is expected to have a specific, fixed set of string keys with specific value types — for example, JSON payloads coming from an external API — while the value at runtime remains an ordinary `dict` object with zero overhead, no new runtime type, and no runtime validation. A static type checker then flags accessing a key that was not declared, or assigning the wrong type to a declared key, catching a whole class of typo and shape-mismatch bugs in code that would otherwise just use ad-hoc, un-typed dictionaries throughout.
Strong answer includes
- declares a fixed set of string keys and value types for a dict shape
- the runtime value is still a plain dict, zero overhead, no runtime validation
- checker flags undeclared keys and type mismatches on assignment
Practical example
class UserPayload(TypedDict):
id: int
name: strlets a checker flag
payload["nam"]as an unknown key or
payload["id"] = "5"as a type mismatch, both common bugs in raw dict-handling code.