Skip to content

Incorrect assignability with union involving TypedDict #3488

Closed

Description

@JelleZijlstra

Summary

On this program:

from typing import TypedDict

class Foo(TypedDict):
    some: str
    name: str

type Bar = dict[int, float]

type Baz = Foo | Bar

baz: Baz = {"some": "foo", "name": "x"}  # OK
bar: Bar = {1: 5.2, 2: 7.4}  # OK

baz2: Baz = {1: 5.2} # error: Expected TypedDict key to be string literal  [misc]

ty outputs

error[missing-typed-dict-key]: Missing required key 'name' in TypedDict `Foo` constructor
  --> main.py:14:13
   |
14 | baz2: Baz = {1: 5.2} # error: Expected TypedDict key to be string literal  [misc]
   |             ^^^^^^^^
   |

error[missing-typed-dict-key]: Missing required key 'some' in TypedDict `Foo` constructor
  --> main.py:14:13
   |
14 | baz2: Baz = {1: 5.2} # error: Expected TypedDict key to be string literal  [misc]
   |             ^^^^^^^^
   |

Found 2 diagnostics

But the program should be accepted; the Baz union includes dict[int, float] and this is a valid dict[int, float].

(From python/typing#2292)

Version

No response

Activity

  1. charliermarsh commented on May 19, 2026

    @charliermarsh
    Member

    I think we maybe need to see through aliases here?

    diff --git a/crates/ty_python_semantic/src/types/infer/builder.rs b/crates/ty_python_semantic/src/types/infer/builder.rs
    index 233d126d5a..730e7af0d7 100644
    --- a/crates/ty_python_semantic/src/types/infer/builder.rs
    +++ b/crates/ty_python_semantic/src/types/infer/builder.rs
    @@ -6164,9 +6164,10 @@ impl<'db, 'ast> TypeInferenceBuilder<'db, 'ast> {
                     let union_elements = union.elements(self.db());
                     let typed_dicts = union_elements
                         .iter()
    -                    .filter_map(|element| element.as_typed_dict())
    +                    .filter_map(|element| element.resolve_type_alias(self.db()).as_typed_dict())
                         .collect_vec();
                     let has_dict_compatible_fallback = union_elements.iter().any(|element| {
    +                    let element = element.resolve_type_alias(self.db());
                         !element.is_typed_dict() && element.is_instance_of(self.db(), KnownClass::Dict)
                     });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions