Skip to content

Dict unpacking fails when used for building TypedDict with required keys #19467

@adamantike

Description

@adamantike

Bug Report

When dict unpacking is used to dynamically add optional keys to a TypedDict, mypy raises a typeddict-item error.
As dict unpacking is used to fill some keys from the TypedDict, my understanding is that mypy could validate the unpacked dictionaries considering all keys as NotRequired, and only the final TypedDict respecting its formal definition.

To Reproduce

Gist: https://mypy-play.net/?mypy=latest&python=3.13&gist=b3377281f7f5a6f83dd9962d60302827

from typing import NotRequired, TypedDict


class Project(TypedDict):
    name: str
    version: NotRequired[str]


def build_project(name: str, version: str | None = None) -> Project:
    return {
        "name": name,
        **({"version": version} if version is not None else {})
    }

Actual Behavior

$ mypy .
main.py:12: error: Missing key "name" for TypedDict "Project"  [typeddict-item]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.17.0
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.13.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions