Skip to content

Type Prediction for union with typeguard looks different from when we do not use typeguradΒ #55961

Closed as not planned
@ryoppippi

Description

@ryoppippi

πŸ”Ž Search Terms

TypeGuard
Union

πŸ•— Version & Regression Information

Works After TS 4.6

⏯ Playground Link

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABDAzgORAG0wCgB4Bci4A1mHAO5gCUReyKiYWmA3gFCJeIBOAplBA8k9ALzimLANzsAvu3ZQAngAc+iAKI8ecHgFUw8MAB4AKgBpEexKM3bdAPhuIA2nsvgAJn2AwwfTwBdRAAfV2ZsS1NAhXZQSFgERCg+FCgcAEMeAHMiLR19QwRjNJ4-bKdqDm5ECAQ01z5tSwA3DMwQPmDbLOzObhhgHABCVAxsHCaeair+mq4oAAsdCkQpmRr5Gv5BYUQ2jvVEAHpjxFLy0OIwb19-TzkFeOgjZNSoACZMnLz7QqMSlAymAKohZjU6mAGi4pq12p1uohenNkEMpohhhIIphwfMFstKGttBtuFtuDshEgDp0TmcLiC5EA

πŸ’» Code

function isNull(x: unknown): x is null{
    return x === null;
}

type ErrorUnion<T, U = Error> = [U, undefined] | [null, T]


function test(arg: ErrorUnion<string> ){
    const [err, value] = arg
    if(!isNull(err)){
        throw err;
    }
    return value  // string | undefined
}

function test2(arg: ErrorUnion<string> ){
    const [err, value] = arg
    if(err !== null){
        throw err;
    }
    return value // string
}

πŸ™ Actual behavior

The value variables in test and test2 are predicted as different types

πŸ™‚ Expected behavior

Both value in test and test2 should be predicted as string

Additional information about the issue

No response

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