Python Type Hints - typing.TypedDict


Python (>=3.8) tip:

You can subclass TypedDict to create a type for dictionaries with fixed keys.

Static type checking will report an error when there are extra or missing keys.

from typing import TypedDict


class Song(TypedDict):
    name: str
    year: int


song: Song = {"name": "Enter Sandman", "year": 1991, "band": "Metallica"}

"""
mypy song.py
song.py:9: error: Extra key "band" for TypedDict "Song"
Found 1 error in 1 file (checked 1 source file)
"""