Skip to content

False positive reportTypedDictNotRequiredAccess when indexing TypedDict after if key in typed_dict guard inside a Literal loop #11575

Description

Environment

  • Pyright Version: 1.1.411
  • Python Version: 3.13.14

Bug Description

When iterating over a tuple of string literal keys (e.g. for key in ("anyOf", "oneOf"):) and guarding a key lookup on a total=False (or NotRequired) TypedDict using if key in typed_dict:, Pyright fails to perform type narrowing on typed_dict[key].

Instead, Pyright raises a false positive reportTypedDictNotRequiredAccess warning:

Could not access item in TypedDict
  "anyOf" is not a required key in "JsonSchema", so access may result in runtime exception
  "oneOf" is not a required key in "JsonSchema", so access may result in runtime exception

Even though if key in typed_dict: guarantees at runtime that key exists before indexing typed_dict[key], Pyright fails to apply narrowing when key is a union of literal string types.


Minimal Code Example (Repro)

pyright playground

from typing import TypedDict


class JsonSchema(TypedDict, total=False):
  anyOf: list['JsonSchema']
  oneOf: list['JsonSchema']


def process_schema(schema: JsonSchema) -> None:
  for keyword in ("anyOf", "oneOf"):
    if keyword in schema:
      reveal_type(keyword)  # Type of "keyword" is "Literal['anyOf', 'oneOf']"
      sub_schemas = schema[keyword]  # reportTypedDictNotRequiredAccess
      print(len(sub_schemas))

Expected Behavior

Pyright should recognize if keyword in schema: as a valid narrowing guard for TypedDict keys when keyword is a Literal["anyOf", "oneOf"] (or a str union of valid TypedDict keys), permitting safe indexing schema[keyword].

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions