Skip to content

Literal key in narrowing for TypedDict w/o extra items #2199

@yangdanny97

Description

@yangdanny97

Describe the Bug

from typing import *

class TD(TypedDict):
    x: int

def test(td: TD):
    if "y" in td:
        td["y"] # unexpected error

Python: 3.12

If we explicitly check the key exists we should not give this error. Naively we could narrow to Any, but this would apply to the whole dict, and would interact weirdly when there is a union

from typing import *

class TD(TypedDict):
    x: int

class TD2(TypedDict):
    x: int
    y: int

def test(td: TD | TD2):
    if "y" in td:
        td["y"] # should this be Any or int | Any ?

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AqADroRAYyio4cOgBUAIgApZzGJnkQxDAJSIRdA3XyJO6BiJGYYYRvAaKGmEwt37DEG0JCkvpxk7dDQ0cAbS8fEABdEAAaEDJKayhSQgZaKAoAYjoABVJEsGS6NCw8fDoxXHRINgBXSlQGCCrCEWyAZRgYOgALBgZiOEQAemGEpJTeNmGYdGHMXDE4YcrqiDqGpqrhujBeOlQAN1RoVGxYCqqa%2Bsbm9DpcYi30OFb0MgYeqoBaQ5hKOB3OgAXjoXgAzIQAIwAJi8IhAAF84qgtBA-gAxaAwCglHAEEjkRFAA

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    narrowingIssues with narrowing - root cause is usually narrowing, flow handling, or bothneeds-discussionAn issue where it's not clear whether there is a bug or we are behaving as expected.typecheckingv1-verifiedIn both V1 milestone and top-ranked (verified by ranking pipeline)

    Type

    No fields configured for Bug.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions