Required marks TypedDict keys as mandatory. NotRequired makes them optional.
1from typing import TypedDict, Required, NotRequired23# Default: all required4class User(TypedDict):5 name: str6 email: str7 age: int89# With total=False: all optional10class UserOptional(TypedDict, total=False):11 name: str12 email: str1314# Mixed: some required, some optional15class UserMixed(TypedDict):16 name: Required[str]17 email: Required[str]18 age: NotRequired[int]19 bio: NotRequired[str]2021# Usage22user: UserMixed = {"name": "Alice", "email": "alice@example.com"} # OK23user: UserMixed = {"name": "Alice", "email": "a@b.com", "age": 25} # OK24# user: UserMixed = {"name": "Alice"} # Error: email is Required2526# With FastAPI27from fastapi import FastAPI2829app = FastAPI()3031class CreateUserRequest(TypedDict):32 name: Required[str]33 email: Required[str]34 age: NotRequired[int]35 bio: NotRequired[str]3637@app.post("/users/")38async def create_user(user: CreateUserRequest):39 return user
Benefits: