Skip to content

Associated literal should narrow type (tagged unions) #643

@aslpavel

Description

@aslpavel

Summary

When you have union with literal attribute it should be possible to narrow based on this attribute
playground

# tagged.py
from dataclasses import dataclass
from typing import Literal, assert_type


@dataclass
class A:
    tag: Literal["A"]
    value: int


@dataclass
class B:
    tag: Literal["B"]
    value: str


type AB = A | B


def test(ab: AB) -> None:
    if ab.tag == "A":
        assert_type(ab.value, int)
$ ty check tagged.py 
WARN ty is pre-release software and not ready for production use. Expect to encounter bugs, missing features, and fatal errors.
error[type-assertion-failure]: Argument does not have asserted type `int`
  --> tagged.py:22:9
   |
20 | def test(ab: AB) -> None:
21 |     if ab.tag == "A":
22 |         assert_type(ab.value, int)
   |         ^^^^^^^^^^^^--------^^^^^^
   |                     |
   |                     Inferred type of argument is `int | str`
   |
info: `int` and `int | str` are not equivalent types
info: rule `type-assertion-failure` is enabled by default

Found 1 diagnostic

Version

ty 0.0.1-alpha.9

Metadata

Metadata

Assignees

No one assigned

    Labels

    narrowingrelated to flow-sensitive type narrowing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions