pyre-check icon indicating copy to clipboard operation
pyre-check copied to clipboard

Type narrowing on TypedDict based on types of entries

Open tmke8 opened this issue 3 years ago • 1 comments

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

tmke8 avatar Jul 31 '22 17:07 tmke8

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).

pradeep90 avatar Aug 01 '22 19:08 pradeep90