This answer tells how to validated a TypedDict at runtime, but it won't catch the case of an extra key being present.
For example, this doesn't throw. How can I make it throw?
from typing import Any, TypeVar
from pydantic import TypeAdapter
from typing_extensions import TypedDict
T = TypeVar('T')
def runtime_check_typed_dict(TypedDictClass: type[T], object_: Any) -> T:
TypedDictValidator = TypeAdapter(TypedDictClass)
return TypedDictValidator.validate_python(object_, strict=True)
class MyThing(TypedDict):
key: str
obj_: Any = {'key': 'stuff', 'extra': 'this should throw!'}
runtime_check_typed_dict(MyThing, obj_)
My Answer
You should set
extra='forbid'.(Documentation) How to config
typing_extensions.TypedDictforpydantic: https://docs.pydantic.dev/2.4/usage/strict_mode/#dataclasses-and-typeddictHere's the example for both
typing_extensions.TypedDictandpydantic.BaseModel.My Example