Skip to content

[nightly] [regression] Control flow analysis for destructured unions gets invalidated by later assignmentΒ #57011

Closed
@MichaelMitchell-at

Description

@MichaelMitchell-at

πŸ”Ž Search Terms

control flow assignment destructured discriminated union

πŸ•— Version & Regression Information

  • This changed between versions 5.3.3 and 5.4.0 nightly

⏯ Playground Link

https://tsplay.dev/mpzrgw

πŸ’» Code

function test({
    other,
    success,
    value,
}: {other: unknown} & (
    | { success: true; value: number }
    | { success: false; value?: number }
)): number {
    if (success) {
        return value;
    //  ^^^^^^^^^^^^^ Type 'number | undefined' is not assignable to type 'number'.
    }

    other = 4; // comment me out and the type error goes away
    return 4;
}

πŸ™ Actual behavior

Type error because value is not narrowed by success check.

πŸ™‚ Expected behavior

No type error because narrowing is correctly applied

Additional information about the issue

Note that this seems to be an extended version of a bug that I discovered has existed since TS 4.6 when control flow analysis for destructured unions was introduced!

function test({
    success,
    value,
}:
    | { success: true; value: number }
    | { success: false; value?: number }): number {
    if (success) {
        return value;
    //  ^^^^^^^^^^^^^ Type 'number | undefined' is not assignable to type 'number'.
    }

    value = 4; // comment me out and the type error goes away
    return 4;
}

Metadata

Metadata

Assignees

Labels

Design LimitationConstraints of the existing architecture prevent this from being fixed

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions