pyre-check
pyre-check copied to clipboard
Type narrowing on TypedDict based on types of entries
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
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).