Skip to content

Should infer not undefined in "else" when checked in compound boolean expression in "if" Β #55331

@yftachman

Description

@yftachman

πŸ”Ž Search Terms

"infer", "undefined", "compound", "boolean expression"

πŸ•— Version & Regression Information

i dont know if this is changed behaviour

⏯ Playground Link

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFDKHJgBcyWUoA5sgD7ICuIAJhDKBMwNx4C+eeGEwRhgAexDFMYAGLCAFHDLosAGmQAjMhrFiANhDggAlPiLIA9BeQAFKGI0GAtsgRwMEAkWAxk8jcgAZIHIAIRwAHRgxrhe5oQIEhj6EBF6YlTyAOQ+WcZxyLzIEHoesfFEVsgAkgByAMIA8gBKzQCi9ajIALTIIGLYTKzsIJzkABZiDHrMmiigMNBQnAXmiSBYmsgAvMiRYBGgrAAejTDZAIx5POb8AuZVAOpiUADW1K7unuY+fgHBeyiMTMFUs1iarQ6XV6-UGLDYHFmCyWK1BriS2ACu32h3hp3OWSuxhuRDuD2szzeHzcHgKv3k4SB5VBVgKRRKZRBFSqEPanR6fQGjHhIzGyKgy2YqyI602WMBByOEHxl2ubL4QA

πŸ’» Code

interface Test {
    t: string | undefined;
}

function testFunc(a: Test, b: boolean){
    // Problem case
    if (b && !a.t) {
        console.log('if')
    } else {
        // INCORRECT - not undefined should be inferred
        const b = a.t.indexOf('1');
    }


    // Working case
    if (b && a.t) {
        // CORRECT - not undefined inferred
        const b = a.t.indexOf('1');
    }

    // Working case
    if (!a.t) {
        //
    } else {
        // CORRECT - not undefined inferred
        const b = a.t.indexOf('1');
    }
}

πŸ™ Actual behavior

a.t was checked to be undefined by if, but in else it is not inferred.

in test case 1, we can see that doing the reverse (checking for defined and checking in "if" for defined works correctly)
in test case 2, we can see that if its not a compound boolean expression it works correctly

πŸ™‚ Expected behavior

inferred type in else should be defined because it was checked in the if

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions