Skip to content

Optional fields in TypedDicts are not reported #18879

Closed as duplicate
Closed as duplicate

Description

@sk-

Bug Report
Optional fields in TypeDicts are not reported, allowing to unsafely access such fields.

To Reproduce

from typing import NotRequired, TypedDict


class Data(TypedDict):
    foo: NotRequired[int]


def extract(data: Data) -> int:
    return data["foo"]


print(extract({}))

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=aa7bfac9b1c70873510bb3e28128f1d4

Expected Behavior
The code should raise a typing error similar to what pyright reports

mypy_typeddict.py:9:12 - error: Could not access item in TypedDict
    "foo" is not a required key in "Data", so access may result in runtime exception (reportTypedDictNotRequiredAccess)
1 error, 0 warnings, 0 informations

This is important because the code above does produce a runtime error.
Actual Behavior

No error is reported

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

Activity

  1. added
    bugmypy got something wrong
    on Apr 4, 2025
  2. brianschubert commented on Apr 4, 2025

    @brianschubert
    Collaborator

    Thanks - closing as duplicate of #12094

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions