Skip to content

Narrow the parent type of a singleton type to never in the false branch #20583

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

Open
weswigham opened this issue Dec 8, 2017 · 1 comment
Open
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@weswigham
Copy link
Member

If the type of the member checked is not falsy (and so is never in the false branch).

TypeScript Version: 2.7.0-dev.201xxxxx

Code

const x: {a: 1, b: 2} = { a: 1, b: 2 };
if (x.a) {

}
else {
    x.a;
}

Expected behavior:
type of x in the else branch is never.

Actual behavior:
type of x is {a: 1. b: 2}, and x.a is (counterintuitively) never.

This would bring the behavior of truthiness guards in line with our new behavior for in type guards.

@WORMSS
Copy link

WORMSS commented Aug 15, 2019

I am not sure if this is exactly similar, but I am getting property doesn't exist on never

abstract class Guards {
    public static isBasic(obj: Base): obj is Basic {
        return obj.type === Type.Basic;
    }
    public static isChainage(obj: Base): obj is Chainage {
        return obj.type === Type.Chainage;
    }
}

enum Type {
    Basic,
    Chainage,
}

interface Base {
    type: Type,
}

interface Basic extends Base {}
interface Chainage extends Base {
    start: number;
    end: number;
}

const ref: Chainage = {
    type: Type.Chainage,
    start: 0,
    end: 1,
}

if ( Guards.isBasic(ref)) {
    // No-op
} else if ( Guards.isChainage(ref)) {
    ref.start // Property 'start' does not exist on 'never'.
}

https://www.typescriptlang.org/play/#code/IYIwzgLgTsDGEAJYBthjAg4gV2FAJhgN4BQC5CADtiMgJawKTAQMJ1gBCaDAFAPYgAVgC4E3MAFMAlGMFD2GCW1IU1CKJIjYoAOwTyAdBACelSQgC81hABUzkw8tgBuMhQC+78tVptmrIwcAMIAFsB0usAA5pICwmISMnLCighhEVGxCKrq5JraegbCxg5WNvbmhhmRMZJual5eJJK62AC2dmW55M4ANN7p4bWxA82REJJQAGZwFkk5g6bmYpWSYyQkE1OzsPM8jJIAHpO6hOJoFkRe2zNzQ5l1CMen5ws9TBB4EGJt7SBTBoUVr4X4dAFQNzNWD8XSQDSSaZiGpZCyWRZqZaSVYOarDVEDNTMKA-BAABkJwLOYgAjBsttMELwsLgCGBDBxnLxNNNpNIMRQAPSChAAOX4AFp+JQSB5nsgpOxGcycHhCBywCi6tzEXyBflEYZiYhhQgAApQaVTUwIADkxttCHw-EkGF0-EQxw4iFhdt0kgAblNbYZZUA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants