NotRequired
is exactly what you are looking for. Optional[int]
means int | None
, but the item is still required. Any item that is annotated as NotRequired[int]
can be ommitted as stated in PEP 655.
Note: If you import Required
or NotRequired
from typing_extensions
(on Python <3.11), you should also import TypedDict
from typing_extensions
.
So if your type-checker supports this feature, it should only complain about missing my_key1
.
# Python >= 3.11
from typing import Optional, NotRequired, TypedDict
# Python < 3.11
from typing import Optional
from typing_extensions import NotRequired, TypedDict
class MyTypedDict(TypedDict):
my_key1: Optional[int]
my_key2: NotRequired[int]
my_variable = MyTypedDict()
# mypy error: Missing key "my_key1" for TypedDict "MyTypedDict"
# pyright error: Argument missing for parameter "my_key1"