Skip to content

Error for nested type guard #14350

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
andy-hanson opened this issue Feb 28, 2017 · 3 comments
Closed

Error for nested type guard #14350

andy-hanson opened this issue Feb 28, 2017 · 3 comments
Labels
Bug A bug in TypeScript
Milestone

Comments

@andy-hanson
Copy link

TypeScript Version: nightly (Version 2.3.0-dev.20170227)

Code

interface Base {
    kind: string;
}

interface A extends Base {
    kind: "a";
}

interface B extends Base {
    kind: "b";
    b: number;
}

declare function isAOrB(x: Base): x is A | B;

function f(x: A | B): void {
    if (x.kind === "b") {
        x.b; // works
    }
}

function g(x: Base): void {
    if (isAOrB(x)) {
        f(x); // works
        if (x.kind === "b") {
            x.b; // error
        }
    }
}

Expected behavior:

No error

Actual behavior:

Error when a type guard is nested inside of another type guard.

@krryan
Copy link

krryan commented Mar 1, 2017

These kinds of issues relating to narrowing being not-quite-clever-enough have caused a number of headaches for me. Would definitely like to see as many cases, at least the easy ones, handled.

@andy-hanson
Copy link
Author

andy-hanson commented Mar 13, 2017

I suspect this is related:

interface Base {
    name?: string;
}

interface A extends Base {
    kind: "A";
}

interface B extends Base {
    kind: "B";
}

function f(x: A | B): void {
    if (x.name && x.kind !== "B") {
        x.name.length; // Error: Object is possibly 'undefined'.
    }
}

@Andarist
Copy link
Contributor

This one was fixed in TS 4.0. The issue can be closed, cc @jakebailey

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

7 participants