fix(types): check specialized generic TypedDict vars against their fields

VJ
4h ago
+131-8

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Summary

Assigning to a state var typed with a specialized generic TypedDict (p: P[str]) went through the Mapping branch of _isinstance. That branch reads the generic's own type arguments as key and value types:

  • P[str]: args[1] raised IndexError and crashed the event handler.
  • P[int]: keys were checked against int, so every valid assignment logged a false Expected field ... to receive type error.

The issue doesn't mention one more case. With nested=0, the depth _type_check_depth() uses in production, isinstance(obj, P) raised TypeError: TypedDict does not support instance and class checks for every assignment.

Changes in reflex_base/utils/types.py:

  • In the Mapping branch, a TypedDict origin is checked with does_obj_satisfy_typed_dict, the same way a plain TypedDict is checked at each depth.
  • does_obj_satisfy_typed_dict resolves a specialization's fields with get_typed_dict_field_types, which substitutes the type arguments (from #7887). It reads __required_keys__ / __closed__ / __extra_items__ from the origin class, because the alias doesn't forward them.
  • In the final except TypeError fallback, a TypedDict origin is checked as a plain dict, which fixes the production depth.

Both new checks sit on paths that only Mapping types or the error fallback reach, so list/tuple/set checks cost nothing extra. typing_extensions.is_typeddict is used so typing_extensions.TypedDict is covered too.

Fixes #7995

Verification

  • Regression tests fail on main (9 failed) and pass with the fix (15 passed):
    • tests/units/reflex_base/utils/test_types.py: P[...], P[...] | None, a generic subclass (_GenericMiddle[str]), a missing required key and a non-dict value at nested=2; outer-type-only checks at nested=0.
    • tests/units/test_state.py::test_assign_specialized_generic_typed_dict_var: handler-style assignments to P[str] and P[int] vars store the value and log nothing. A non-dict assignment logs the exact expected error.
  • uv run pytest tests/units: 15792 passed, 17 failed. All 17 also fail on unmodified main on my Windows machine. They are symlink tests in tests/units/assets/test_assets.py, test_gradient_profile.py::test_create_resolves_shared_asset and test_utils.py::test_initialize_agents_md_handles_symlinked_claude.
  • uv run ruff check . and uv run ruff format --check . pass. uv run pyright reflex tests packages/reflex-base/src reports the same errors as main, with no new ones.
  • News fragment: packages/reflex-base/news/+7995.bugfix.md.