Skip to content

Type narrowing for LiteralString does not work #3466

@bryanforbes

Description

@bryanforbes

Describe the bug
Given the following code:

from collections.abc import Sequence
from typing import Any, TypeGuard
from typing_extensions import LiteralString, reveal_type


def _is_literal_string(obj: Any) -> TypeGuard[LiteralString]:
    return isinstance(obj, str)


def foo(s: str | Sequence[str]) -> None:
    if isinstance(s, str):
        reveal_type(s)
    else:
        reveal_type(s)


def bar(s: LiteralString | Sequence[LiteralString]) -> None:
    if _is_literal_string(s):
        reveal_type(s)
    else:
        reveal_type(s)

The output on the command line is as follows:

test.py:8:21 - information: Type of "s" is "str"
test.py:10:21 - information: Type of "s" is "Sequence[str]"
test.py:19:21 - information: Type of "s" is "LiteralString"
test.py:21:21 - information: Type of "s" is "LiteralString | Sequence[LiteralString]"

Expected behavior
The type reported on line 21 should be Sequence[LiteralString].

VS Code extension or command-line
Are you running pyright as a VS Code extension or a command-line tool?
Command line

Which version?
1.1.247

Metadata

Metadata

Assignees

No one assigned

    Labels

    as designedNot a bug, working as intended

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions