Skip to content

Union types are not being narrowed correctly in generic functions in 4.3 #44404

Closed
@TomPeters

Description

@TomPeters

Bug Report

Narrowing of a union type based on generic types does not work correctly in else branches in TS 4.3.

This likely relates to the changes made in #43183

🔎 Search Terms

generic, narrow, union types, 4.3

🕗 Version & Regression Information

This changed between versions 4.2.3 and 4.3

⏯ Playground Link

Playground link

💻 Code

function needsToNarrowTheType<First extends { foo: string }, Second extends { bar: string }>(thing: First | Second) {
    if (hasAFoo(thing)) {
        console.log(thing.foo);
    }
    else {
        // I would expect this to work because the type should be narrowed in this branch to `Second`
        console.log(thing.bar); // Error: Property 'bar' does not exist on type 'First | Second'.
    }

    function hasAFoo(value: First | Second): value is First {
        return "foo" in value;
    }
}

🙁 Actual behavior

In the else branch, the type of thing is First | Second.

🙂 Expected behavior

In the else branch. the type of thing is Second.

Metadata

Metadata

Assignees

Labels

Fix AvailableA PR has been opened for this issueNeeds InvestigationThis issue needs a team member to investigate its status.RescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions