-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added support for "tagged union" type narrowing when the conditional …
…expression is of the form `x[K] == V` or `x[K] != V` where `x` is a union of TypedDict objects and `K` is a literal str key value that refers to a field with a literal type and `V` is a literal value.
- Loading branch information
1 parent
c52c928
commit eced7b5
Showing
4 changed files
with
111 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
packages/pyright-internal/src/tests/samples/typeNarrowing22.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# This sample tests type narrowing based on key accesses | ||
# to unions of TypedDicts that have fields with literal types. | ||
|
||
from typing import Literal, TypedDict, Union | ||
|
||
|
||
class NewJobEvent(TypedDict): | ||
tag: Literal["new-job"] | ||
job_name: str | ||
config_file_path: str | ||
|
||
|
||
class CancelJobEvent(TypedDict): | ||
tag: Literal[2] | ||
job_id: int | ||
|
||
|
||
class OtherEvent(TypedDict): | ||
tag: Literal["other-job"] | ||
message: str | ||
|
||
|
||
Event = Union[NewJobEvent, CancelJobEvent, OtherEvent] | ||
|
||
|
||
def process_event(event: Event) -> None: | ||
if event["tag"] == "new-job": | ||
t1: Literal["NewJobEvent"] = reveal_type(event) | ||
event["job_name"] | ||
elif event["tag"] == 2: | ||
t2: Literal["CancelJobEvent"] = reveal_type(event) | ||
event["job_id"] | ||
else: | ||
t3: Literal["OtherEvent"] = reveal_type(event) | ||
event["message"] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters