Skip to content

Nested if statement invalidates type guards #20504

Closed
@kujon

Description

@kujon

TypeScript Version: 2.6.2

Code

type A = {
    id?: string;
    type: 'bar'
};

type B = {
    id?: string;
    type: 'foo';
};

type C = A | B;

const logId = (id: string) => console.log('id', id);

const doSomething = (value: C) => {
    if (value.id) {

        logId(value.id); // This is fine 

        if (value.type === 'foo') { 
            logId(value.id); // Type 'undefined' is not assignable to type 'string'.
        }
    }
};

The above would work just fine, if C was defined as:

type C = {
    id?: string;
    type: 'foo' | 'bar';
};

Expected behavior:

The example above compiles.

Actual behavior:

The type guard checks are invalidated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions