Skip to content

Discriminated union does not narrow based on falsy conditional #27059

Closed
@kevinder

Description

@kevinder

TypeScript Version: 3.0 (current Playground)

Search Terms: Discriminated union falsy false

Code

interface True {
    value: true;
    trueString: string;
}
interface False {
    value: false;
    falseString: string;
}

type TrueOrFalse = True | False;
let x: TrueOrFalse;

if (!x.value) {
    // DOES NOT COMPILE:
    // Property 'falseString' does not exist on type 'TrueOrFalse'.
    //   Property 'falseString' does not exist on type 'True'.
    x.falseString;
}

if (x.value) {
    x.trueString;
} else {
    // SAME ERROR AS ABOVE
    x.falseString;
}

if (x.value === false) {
    // WORKS
    x.falseString;
}

if (x.value === true) {
    x.trueString;
} else {
    // WORKS
    x.falseString;
}

Expected behavior:
Discriminated union is narrowed within falsy conditional blocks.

Actual behavior:
Discriminated union is not narrowed within (!falsy) conditional block, or within else block of a (truthy) conditional.

Playground Link:
http://www.typescriptlang.org/play/#src=interface%20True%20%7B%0D%0A%20%20%20%20value%3A%20true%3B%0D%0A%20%20%20%20trueString%3A%20string%3B%0D%0A%7D%0D%0Ainterface%20False%20%7B%0D%0A%20%20%20%20value%3A%20false%3B%0D%0A%20%20%20%20falseString%3A%20string%3B%0D%0A%7D%0D%0A%0D%0Atype%20TrueOrFalse%20%3D%20True%20%7C%20False%3B%0D%0Alet%20x%3A%20TrueOrFalse%3B%0D%0A%0D%0Aif%20(!x.value)%20%7B%0D%0A%20%20%20%20%2F%2F%20DOES%20NOT%20COMPILE%3A%0D%0A%20%20%20%20%2F%2F%20Property%20'falseString'%20does%20not%20exist%20on%20type%20'TrueOrFalse'.%0D%0A%20%20%20%20%2F%2F%20%20%20Property%20'falseString'%20does%20not%20exist%20on%20type%20'True'.%0D%0A%20%20%20%20x.falseString%3B%0D%0A%7D%0D%0A%0D%0Aif%20(x.value)%20%7B%0D%0A%20%20%20%20x.trueString%3B%0D%0A%7D%20else%20%7B%0D%0A%20%20%20%20%2F%2F%20SAME%20ERROR%20AS%20ABOVE%0D%0A%20%20%20%20x.falseString%3B%0D%0A%7D%0D%0A%0D%0Aif%20(x.value%20%3D%3D%3D%20false)%20%7B%0D%0A%20%20%20%20%2F%2F%20WORKS%0D%0A%20%20%20%20x.falseString%3B%0D%0A%7D%0D%0A%0D%0Aif%20(x.value%20%3D%3D%3D%20true)%20%7B%0D%0A%20%20%20%20x.trueString%3B%0D%0A%7D%20else%20%7B%0D%0A%20%20%20%20%2F%2F%20WORKS%0D%0A%20%20%20%20x.falseString%3B%0D%0A%7D%0D%0A

Related Issues:
None found.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions