Python developers frequently work with dictionaries to represent API responses, configuration settings, database records, and JSON payloads. Dictionaries are flexible, but that flexibility can make large applications difficult to maintain. A dictionary can contain missing keys, unexpected fields, or values with incorrect types without Python reporting a problem immediately.
Python's TypedDict helps address this issue by describing the expected structure of a dictionary. It allows developers to define which keys should exist and what types of values they should contain. Static type checkers can then identify many dictionary-related mistakes before the application runs.
Python 3.15 introduces important improvements to TypedDict through PEP 728. Developers can now use the closed and extra_items class arguments to describe how a dictionary should handle additional keys. This makes it easier to model both strict data structures and dictionaries that allow controlled extensions.
In this article, you will learn how TypedDict works, how to define required and optional fields, how to use the new Python 3.15 features, and how to apply them to practical application scenarios.
What Is TypedDict in Python?
TypedDict is a special construct from the typing module that allows developers to define the expected structure of a dictionary.
Unlike a regular dictionary annotation, which generally describes the types of keys and values, TypedDict defines individual fields with their own types.
Consider a regular dictionary containing customer information:
customer = {
"customer_id": 101,
"name": "Alex",
"email": "[email protected]",
"is_active": True
}
A regular dictionary annotation might describe this structure as:
customer: dict[str, int | str | bool]
However, this annotation does not describe which keys should exist. It only specifies that the keys are strings and the values can be integers, strings, or booleans.
TypedDict provides a more precise definition.
from typing import TypedDict
class Customer(TypedDict):
customer_id: int
name: str
email: str
is_active: bool
customer: Customer = {
"customer_id": 101,
"name": "Alex",
"email": "[email protected]",
"is_active": True
}
Now a static type checker can identify problems such as a missing required field or an incorrectly typed value.
For example:
customer: Customer = {
"customer_id": "101",
"name": "Alex",
"email": "[email protected]",
"is_active": True
}
A type checker reports an error because customer_id is expected to be an integer, not a string.
One important detail is that TypedDict does not create a special dictionary object at runtime. Its instances are ordinary Python dictionaries. Type checking is generally performed by external tools such as mypy or Pyright, not automatically by the Python interpreter.
Creating a TypedDict in Python 3.15
The class-based syntax is the most common way to define a TypedDict.
from typing import TypedDict
class Product(TypedDict):
product_id: int
product_name: str
price: float
available: bool
product: Product = {
"product_id": 501,
"product_name": "Wireless Keyboard",
"price": 49.99,
"available": True
}
Each annotation describes the expected value type for its corresponding key.
You can use common Python types, including:
- str for text values.
- int for integer values.
- float for decimal values.
- bool for Boolean values.
- list[str] for lists of strings.
- dict[str, int] for dictionaries with string keys and integer values.
- Custom classes and other TypedDict definitions for nested structures.
For example, a product can contain a list of tags and a nested supplier object.
from typing import TypedDict
class Supplier(TypedDict):
supplier_id: int
supplier_name: str
class Product(TypedDict):
product_id: int
product_name: str
tags: list[str]
supplier: Supplier
product: Product = {
"product_id": 501,
"product_name": "Wireless Keyboard",
"tags": ["electronics", "computer-accessories"],
"supplier": {
"supplier_id": 20,
"supplier_name": "Tech Supplies"
}
}
This approach is useful when working with complex API responses or nested JSON structures.
Understanding Required and Optional Fields
By default, all fields defined in a TypedDict are required.
Sometimes an API response contains fields that may or may not be present. For example, a customer might have a phone number, but the API does not require it for every customer.
Python provides NotRequired to describe such fields.
from typing import TypedDict, NotRequired
class Customer(TypedDict):
customer_id: int
name: str
email: str
phone: NotRequired[str]
customer: Customer = {
"customer_id": 101,
"name": "Alex",
"email": "[email protected]"
}
The phone field can be omitted without violating the TypedDict definition.
You can also use Required when you want to define a dictionary where fields are optional by default but selected fields must always exist.
from typing import TypedDict, Required
class CustomerUpdate(TypedDict, total=False):
customer_id: Required[int]
name: str
email: str
phone: str
update: CustomerUpdate = {
"customer_id": 101,
"email": "[email protected]"
}
Here, customer_id is required, while the remaining fields are optional.
The total=False argument makes fields optional by default. Required overrides that behavior for an individual field.
What's New in Python 3.15 TypedDict?
Before Python 3.15, TypedDict already supported required fields, optional fields, inheritance, generic types, and read-only fields.
However, developers had less control over additional dictionary keys in the type definition.
Python 3.15 adds support for two important class arguments:
These features are introduced through PEP 728.
They address two different requirements. The closed argument describes a dictionary that must not contain additional keys according to the type system. The extra_items argument describes a dictionary that allows additional keys when their values follow a specified type.
Using closed=True to Define Strict Dictionaries
By default, TypedDict is open. This means the type definition does not declare a closed set of keys, and additional keys can be present in compatible dictionary values.
In some applications, accepting unexpected fields is undesirable. For example, an internal configuration object may need a fixed structure.
Python 3.15 allows developers to define a closed TypedDict.
from typing import TypedDict
class ApplicationConfig(TypedDict, closed=True):
app_name: str
environment: str
debug: bool
port: int
config: ApplicationConfig = {
"app_name": "Inventory API",
"environment": "production",
"debug": False,
"port": 8080
}
The closed=True argument tells the type system that additional keys are not permitted.
For example:
config: ApplicationConfig = {
"app_name": "Inventory API",
"environment": "production",
"debug": False,
"port": 8080,
"region": "Asia"
}
A compatible static type checker should report an error because region is not declared in ApplicationConfig.
The closed option is useful for internal data contracts where the expected fields are known and unexpected fields should be rejected during static analysis.
It is important to understand that closed=True does not automatically validate dictionaries at runtime. If untrusted JSON contains an additional field, Python does not automatically reject it just because the receiving variable has a closed TypedDict annotation.
Runtime validation still requires explicit application logic or a validation library.
Using extra_items to Allow Additional Fields
Some dictionary structures have a known set of fields but also need to support additional values.
For example, an API response might contain standard customer information along with dynamically generated metadata.
Before Python 3.15, developers often used a broad dictionary type or separate structures to describe this kind of data.
The extra_items argument provides a more precise solution.
from typing import TypedDict
class CustomerMetadata(TypedDict, extra_items=str):
customer_id: int
name: str
email: str
customer: CustomerMetadata = {
"customer_id": 101,
"name": "Alex",
"email": "[email protected]",
"department": "Engineering",
"region": "Asia",
"membership": "Premium"
}
The declared fields retain their individual types. Additional fields are allowed, but their values must be strings.
For example, this dictionary contains an invalid additional value:
customer: CustomerMetadata = {
"customer_id": 101,
"name": "Alex",
"email": "[email protected]",
"department": 25
}
A type checker should report an error because department is an additional field and its value must be a string.
This is useful when an API has stable core fields but supports extensible metadata.
Understanding closed and extra_items
The two options solve different problems.
Feature | Purpose | Additional keys |
|---|
Default TypedDict | Defines a normal open dictionary type | Allowed by the open typing model |
closed=True | Defines a closed dictionary type | Not allowed |
extra_items=str | Allows additional fields with string values | Allowed when values are strings |
extra_items=int | Allows additional fields with integer values | Allowed when values are integers |
The closed and extra_items arguments cannot be used together in the same TypedDict definition.
Choose closed=True when the structure should not have additional keys. Choose extra_items when additional keys are expected but their value type must remain consistent.
Using TypedDict for API Request and Response Models
One of the most practical uses of TypedDict is describing API request and response payloads.
Consider an application that receives customer registration requests. The request contains required information and optional preferences.
from typing import TypedDict, NotRequired
class CustomerRegistration(TypedDict):
name: str
email: str
password: str
phone: NotRequired[str]
marketing_enabled: NotRequired[bool]
def register_customer(
customer: CustomerRegistration
) -> str:
return f"Customer registered: {customer['email']}"
new_customer: CustomerRegistration = {
"name": "Alex",
"email": "[email protected]",
"password": "SecurePassword123",
"marketing_enabled": True
}
print(register_customer(new_customer))
This definition makes the expected request structure clear.
It also helps developers maintain consistency between API handling functions and the data structures passed to them.
However, a TypedDict is not a replacement for request validation. The application must still validate user input, enforce password policies, check email formats, and handle missing or invalid values at runtime.
Using TypedDict for Flexible JSON Metadata
Consider an application that stores user activity information. Every record has a user ID, an event name, and a timestamp. Additional metadata depends on the event.
For example, a login event may contain a device name, while a purchase event may contain an order ID.
You can model the shared fields and allow additional metadata with extra_items.
from typing import TypedDict
class ActivityEvent(TypedDict, extra_items=str):
user_id: int
event_name: str
timestamp: str
login_event: ActivityEvent = {
"user_id": 101,
"event_name": "login",
"timestamp": "2026-12-04T10:30:00",
"device": "Windows Desktop",
"browser": "Edge"
}
purchase_event: ActivityEvent = {
"user_id": 101,
"event_name": "purchase",
"timestamp": "2026-12-04T11:15:00",
"order_id": "ORD-501",
"payment_method": "Card"
}
The example uses strings for all additional values. If the application needs metadata values of different types, you can choose an appropriate union type.
from typing import TypedDict
class ActivityEvent(TypedDict, extra_items=str | int | bool):
user_id: int
event_name: str
timestamp: str
event: ActivityEvent = {
"user_id": 101,
"event_name": "purchase",
"timestamp": "2026-12-04T11:15:00",
"order_id": "ORD-501",
"amount": 2500,
"successful": True
}
This gives developers a useful balance between a known event structure and flexible metadata.
Combining TypedDict With ReadOnly Fields
Python 3.13 introduced ReadOnly for TypedDict fields. Python 3.15 continues to support it alongside the new closed and extra_items features.
ReadOnly tells static type checkers that a field should not be modified through that TypedDict interface.
from typing import TypedDict, ReadOnly
class UserProfile(TypedDict):
user_id: ReadOnly[int]
username: str
email: str
def update_profile(profile: UserProfile) -> None:
profile["username"] = "alex_updated"
profile["email"] = "[email protected]"
# A static type checker reports an error here.
profile["user_id"] = 202
The user_id field is read-only, while username and email remain mutable.
You can combine ReadOnly with closed=True when defining a fixed structure.
from typing import TypedDict, ReadOnly
class SystemIdentity(TypedDict, closed=True):
system_id: ReadOnly[int]
system_name: str
version: str
Remember that ReadOnly is also a static typing feature. It does not make the underlying dictionary immutable at runtime.
Understanding TypedDict Inheritance
TypedDict supports inheritance, allowing developers to reuse common fields across related structures.
For example, an application may have a common user definition and separate definitions for customers and administrators.
from typing import TypedDict, NotRequired
class BaseUser(TypedDict):
user_id: int
username: str
email: str
class Customer(BaseUser):
membership: str
phone: NotRequired[str]
class Administrator(BaseUser):
access_level: int
department: str
Both Customer and Administrator inherit the common fields from BaseUser.
Python 3.15 also supports inheritance rules involving closed and extra_items TypedDict definitions.
For example, a closed TypedDict cannot be extended by adding new fields through a subclass.
from typing import TypedDict
class BaseConfig(TypedDict, closed=True):
application: str
version: str
# A type checker reports an error because BaseConfig is closed.
class ExtendedConfig(BaseConfig):
environment: str
When designing reusable structures, decide whether the base definition should be extensible before using closed=True.
Inspecting TypedDict Definitions at Runtime
Although TypedDict does not validate dictionary values at runtime, its definition exposes metadata that can be useful for introspection.
For example, you can inspect required and optional keys.
from typing import TypedDict, NotRequired
class Employee(TypedDict):
employee_id: int
name: str
department: NotRequired[str]
print(Employee.__required_keys__)
print(Employee.__optional_keys__)
Python 3.15 also provides metadata for the new features.
from typing import TypedDict, NoExtraItems
class StrictRecord(TypedDict, closed=True):
record_id: int
name: str
class FlexibleRecord(TypedDict, extra_items=str):
record_id: int
name: str
print(StrictRecord.__closed__)
print(FlexibleRecord.__closed__)
print(StrictRecord.__extra_items__)
print(FlexibleRecord.__extra_items__)
The closed attribute describes the closed argument. The extra_items attribute describes the additional-item type or returns NoExtraItems when no extra_items argument was specified.
These attributes are useful for tools that inspect type definitions, generate documentation, or build developer utilities.
They should not be treated as a substitute for validating incoming data.
TypedDict vs Regular Dictionary vs Dataclass
Python offers several ways to represent structured data. Choosing the right one depends on how the application uses that data.
Feature | TypedDict | Regular dict | Dataclass |
|---|
Main purpose | Type-check dictionary structures | Store flexible key-value data | Represent structured objects |
Declared fields | Yes | No | Yes |
Static type checking | Supported | Limited without detailed annotations | Supported |
Runtime validation | No automatic validation | No automatic validation | No automatic validation by default |
Dictionary representation | Yes | Yes | No, instances are objects |
Field access | Dictionary keys | Dictionary keys | Attributes |
Additional keys | Controlled through typing rules | Generally unrestricted | Not part of the declared fields by default |
Best use case | JSON and dictionary-based data | Dynamic data | Object-oriented application models |
Use TypedDict when the data should remain a dictionary but needs a well-defined structure.
Use a dataclass when the application benefits from object behavior, methods, and attribute-based access.
Use a regular dictionary when the structure is genuinely dynamic and detailed field-level typing is not required.
Best Practices for Using TypedDict
Define Required Fields Clearly
Use required fields for information that must always be present. Avoid making every field optional simply because some API responses contain incomplete data.
A clear definition helps type checkers identify missing information early.
Use NotRequired for Optional Keys
Use NotRequired when a field may be absent. Do not confuse an optional key with a required key that can contain None.
For example, these definitions express different requirements:
from typing import TypedDict, NotRequired
class Example(TypedDict):
optional_value: NotRequired[str]
nullable_value: str | None
The first key can be omitted. The second key must exist, but its value can be None.
Use closed=True for Strict Contracts
Closed TypedDict definitions are useful for internal configuration structures, fixed payload formats, and contracts where unexpected fields should be detected by static analysis.
Avoid using closed=True for data structures that are intentionally designed to accept extensions.
Use extra_items for Controlled Extensions
When a dictionary needs additional fields, specify the expected value type through extra_items.
For example, extra_items=str is more precise than allowing arbitrary values when all additional metadata should be textual.
Keep Runtime Validation Separate
TypedDict does not automatically validate data received from an API, file, database, or user input.
Validate untrusted data before treating it as a trusted application model. Use explicit validation logic or a suitable validation library when runtime guarantees are required.
Use a Static Type Checker
TypedDict provides its greatest value when combined with a static type checker.
Run mypy or Pyright as part of the development workflow or CI pipeline. This helps catch missing fields, incorrect value types, and incompatible dictionary structures before deployment.
Common Mistakes When Using TypedDict
Assuming TypedDict Validates Data at Runtime
A TypedDict annotation does not automatically inspect a dictionary when it is created.
A dictionary containing an incorrect value can still exist at runtime. Use validation when processing external data.
Confusing NotRequired With None
NotRequired means that a key may be missing. A type such as str | None means that the key must exist but can contain either a string or None.
Choose the definition that matches the actual data contract.
Using closed and extra_items Together
The closed and extra_items class arguments cannot be used together.
Use closed=True to reject additional keys in the typing model. Use extra_items when additional keys are allowed with a specified value type.
Assuming ReadOnly Makes a Dictionary Immutable
ReadOnly restricts modifications through the declared TypedDict interface for static type checking. It does not make the underlying dictionary immutable at runtime.
Ignoring Type Checker Compatibility
Python 3.15 introduces the new TypedDict features, but developers should ensure their chosen type checker supports PEP 728.
An older type checker may not understand closed or extra_items correctly, even when the Python interpreter supports them.
Advantages and Disadvantages of TypedDict
Advantages | Disadvantages |
|---|
Defines clear dictionary structures | Does not provide automatic runtime validation |
Helps identify incorrect fields during development | Requires a compatible static type checker |
Supports required and optional fields | Can become verbose for deeply nested structures |
Supports inheritance and reusable definitions | Does not provide dataclass-style object behavior |
Python 3.15 supports closed and typed additional fields | Advanced typing rules require careful design |
Works naturally with dictionary-based JSON data | Type annotations alone cannot guarantee external data quality |
Conclusion
TypedDict is a practical way to describe structured dictionaries in Python applications. It gives developers better control over field names, value types, required fields, and optional fields while keeping data in the familiar dictionary format.
Python 3.15 makes TypedDict more flexible through the closed and extra_items class arguments introduced by PEP 728. Developers can now describe fixed dictionary contracts or allow additional fields with a clearly defined value type.
These improvements are particularly useful when working with API payloads, JSON metadata, application configuration, and event-driven systems.
For reliable applications, combine TypedDict with a compatible static type checker and explicit runtime validation for external data. This approach keeps dictionary-based code flexible while making its expected structure easier to understand, maintain, and review.
PythonTypedDictPython 3.15PEP 728type hintsstatic type checkingdictionaries
Join the conversation! Your thoughts help the community grow.