diff --git a/docs/source/typed_dict.rst b/docs/source/typed_dict.rst index bbb10a12abe8..75750b571208 100644 --- a/docs/source/typed_dict.rst +++ b/docs/source/typed_dict.rst @@ -289,6 +289,32 @@ need to give each TypedDict the same key where each value has a unique :ref:`Literal type `. Then, check that key to distinguish between your TypedDicts. +You can also use ``@final`` to indicate that the TypedDict definition will not be +subclassed. This allows mypy to do type refinement based on unique properties of +the TypedDict: + +.. code-block:: python + + from typing import TypedDict, final + + @final + class Movie(TypedDict): + director: str + runtime: int + + @final + class Book(TypedDict): + author: str + pages: int + + def foo(movie_or_book: Movie | Book) -> None: + if 'director' in movie_or_book: + director = movie_or_book['director'] + runtime = movie_or_book['runtime'] + elif 'author' in movie_or_book: + author = movie_or_book['author'] + pages = movie_or_book['pages'] + Inline TypedDict types ----------------------