Skip to content

Type isn't narrowed if used after conditionally calling class method with never as return type #36753

@Newbytee

Description

@Newbytee

TypeScript Version: 3.8.0-dev.20200211

Search Terms: type narrowing typescript function

Code

class ThrowingClass {
    public thrower(): never {
        throw new Error("oh no!");
    }
}

function needs_narrowing(): string | null {
    if (Math.random() > 0.5) {
        return "Narrow me";
    } else {
        return null;
    }
}

function string_needer(value: string): void {
    console.log(value);
}

const throwing_class = new ThrowingClass();

const to_narrow = needs_narrowing();

if (to_narrow === null) {
    throwing_class.thrower();
}

string_needer(to_narrow);

Expected behavior: TypeScript compiler sees that the method of the instantiated class never returns and therefore deduces that this is safe, like it does in standalone functions and static methods (see "Working example").

Actual behavior: TypeScript compiler does not consider whether the method of the instantiated class never returns and therefore deduces that this is unsafe.

Playground Link:
Broken example:
https://www.typescriptlang.org/play/index.html?ts=3.8.0-dev.20200211#code/MYGwhgzhAEAqAWAnA9gdwJYDsDmBhcU0A3gLABQ0l0ADgK4BGI6w0ALkmgKaIAUAlAC5omTgDduxclWlsOqYZ3kBRRCl4AiZPGHIAhOr4BuKVQC+5c2XIAzWpmCt0yTAs4ATCAH1MYVWizY-EIQrIgB0AA+wrQgIJIUVOjW0DwAsmDsAHSIYJhuyAC2-NAAfNAADJkArHzxMlSInKy0iC7qAHK+KPIFnOrGCZSm0JwgEJx19dCNza3RsQPSlpY2dg5OLiFhON6c7tw8omAgtJzBoQGC0KLI6G6TlMDOEMggnJkgyIFHJ5xGFuRyE9MCFZN0Ap5QJAYABeBTyBDgnD4aH8AZA56sNjIbxdNDQOEidxeHx+DA4NGAshJFKsHGk7oEmGEmIgWqkQZg-w7KFQTLsboHf5kFZkLYQoluA503Fk4VAA

"Working" example (using static method):
https://www.typescriptlang.org/play/index.html?ts=ts=3.8.0-dev.20200211#code/MYGwhgzhAEAqAWAnA9gdwJYDsDmBhcU0A3gLABQ0l0ADgK4BGI6w0EALmG89G0mgKaIAFAEoAXNEz8AboOLkqinn1ST+qgKKIUwgETJ4k5AEJdIgNwKqAX3K2y5AGa1MwLskxr+AEwgB9TDBtNCxsUQl2RFDoAB9JWhAQeQoqdEdoIQBZTngAOkQwTG9kAFtRaAA+aAAGXIBWEWSlKkR+NlpET10AOSCUVRL+XUsUymtofhAIfibm6Fb2zvjEkcV7eycXN3QPVjYonAD+H0EhaTAQWn4I-dDxaGlkdG9ZymAPCGQQflyQZDDzpd+BY7ORyO9MOxlP1Qn5QJAYABeNSqBAwnD4BGiEbgj5sHjIAJ9NDQZFSHz+QLBDA4bFgshpDJsQlU-qkxFkhIgRqkUZwFShTFQXK8fqnEFkDZkSKw8neU7MonUiVAA

Related Issues: #12825, #25542

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions