Skip to content

Use type context from __setitem__ signature to inform the type inferred on the right-hand side of subscript assignments #2136

@nwalters512

Description

@nwalters512

Summary

Consider this code:

from typing import TypedDict


class Bar(TypedDict):
    baz: float

foo: dict[str, Bar] = { "a": { "baz": 1 } }

foo["b"] = { "baz": 2 }

I would expect the assignment on the last line to be considered correct/valid, and this is how Pyright (playground link) and mypy (playground link) treat it. However, ty reports an error:

Invalid subscript assignment with key of type `Literal["b"]` and value of type `dict[Unknown | str, Unknown | int]` on object of type `dict[str, Bar]` (invalid-assignment) [Ln 9, Col 1]

The initial assignment/initialization of foo demonstrates that ty can correctly infer that a plain dictionary ({ "baz": 1 }) is assignable to type Bar; it just seemingly can't do that for a later assignment to a dictionary's items.

Playground link: https://play.ty.dev/8b35242f-36a7-4cb3-9e15-8416f0c509de

Version

ty 0.0.5 (d37b7db 2025-12-20)

Metadata

Metadata

Assignees

Labels

bidirectional inferenceInference of types that takes into account the context of a declared type or expected typebugSomething isn't working

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions