Skip to content

T1 | T2 narrows to T1 and T1 | T2 #19342

Open
@bukzor

Description

@bukzor

I feel confident that x should have type T2 in the else clause here. Instead, it has type T1 | T2 which doesn't seem at all consistent.

from typing import TypeVar

from typing_extensions import assert_type

T1 = TypeVar("T1")
T2 = TypeVar("T2")


def f(x: T1 | T2, type1: type[T1]) -> T1 | T2:
    t1: T1
    t2: T2
    if isinstance(x, type1):
        # mismatch(pyright): expected "T1@f" but received "object* | T1@f"
        assert_type(x, T1)
        t1 = x
        assert_type(t1, T1)
        return t1
    else:
        # mismatch(pyright): expected "T2@f" but received "object*"
        # error(mypy): Expression is of type "T1 | T2", not "T2"
        assert_type(x, T2)

        # error(pyright): Type "object*" is not assignable to declared type "T2@f"
        # error(mypy): Incompatible types in assignment (expression has type "T1 | T2", variable has type "T2")
        t2 = x

        assert_type(t2, T2)
        return t2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions