TypedDict defines dictionary schemas with type hints.
1from typing import TypedDict, Required, NotRequired23class UserDict(TypedDict):4 name: str5 email: str6 age: int7 bio: NotRequired[str] # Optional key89class ProductDict(TypedDict, total=False):10 name: Required[str] # Required key11 price: float12 description: str1314# Usage15user: UserDict = {16 "name": "Alice",17 "email": "alice@example.com",18 "age": 2519}2021# With defaults22from typing import TypeGuard2324def is_user_dict(data: dict) -> TypeGuard[UserDict]:25 return (26 "name" in data and27 "email" in data and28 "age" in data29 )3031def process(data: dict):32 if is_user_dict(data):33 print(data["name"]) # Type-safe access3435# Inheriting36class ExtendedUser(UserDict):37 role: str38 is_active: bool
Use cases: