facebook / pyre-check

Performant type-checking for python.
https://pyre-check.org/
MIT License
6.87k stars 437 forks source link

Type narrowing on TypedDict based on types of entries #644

Open tmke8 opened 2 years ago

tmke8 commented 2 years ago

Pyre Feature Request

When you have a Union of TypedDict it would be nice to be able to narrow them. However, pyre doesn't seem to allow this. Even when using Final!

from typing import Final, Literal, TypedDict, Union
from typing_extensions import TypeAlias

class A(TypedDict):
    tag: Literal["a"]
    foo: int

class B(TypedDict):
    tag: Literal["b"]
    bar: str

AB: TypeAlias = Union[A, B]

def f() -> AB:
    return {"tag": "a", "foo": 4}

def g() -> int:
    ab: Final[AB] = f()
    if ab["tag"] == "a":
        return ab["foo"]  # error: "TypedDict accessed with a missing key [27]: TypedDict `B` has no key `foo`."
    return 0
pradeep90 commented 2 years ago

Yeah, we'd like to support this, but I don't think we'll get to it any time in 2022 (internal tracking task: T61938090).