Skip to content

Ternary branches not checkedΒ #61578

Closed as not planned
Closed as not planned
@00001H

Description

@00001H

πŸ”Ž Search Terms

"ternary" "ts2322"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.0-dev.20250414#code/GYVwdgxgLglg9mABAZwBZxAGwCYH0BGAprsDGIQBQCCAXImCALZEBOiAPvVpgDSIBCdBs0JtODTJgCUQpqwDeAKEQrEMYBUTVEAXj1dJUxAH4t-RAEJ9E6YjoVzenYipGpS1Z8QtCUECyR+AG5lVQBfUJUfPwDEAAYQsKA

πŸ’» Code

function should_be_fine(A: number | null, B: number | null): number{
    if( (A === null) ? (B !== null) : (B === A) ){
        return B; // <-- error here
    }
    return 0;
}

πŸ™ Actual behavior

I got a 2322 on the return B; line, saying that B is of type number | null which is not compatible with the return type number.

πŸ™‚ Expected behavior

It's obvious that B cannot be null: Depending on the ternary branch, either B !== null or B === A && A !== null must be true. Therefore, the B in return B; should have number type and the statement should compile without error.

Additional information about the issue

Replacing the if condition with (B !== null) || (B === A && A !== null) fails with the same error. In fact

function should_be_even_finer(A: number | null, B: number | null): number{
    if( true ? (B !== null) : (B !== null) ){
        return B;
    }
    return 0;
}

is the weakest form that still fails to compile, and might be a good starting point. (it reveals that ternaries are under-checked; at the very least, exprA ? exprB : exprC should imply exprA && exprB || !exprA && exprC)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions