Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@TomPeters

Description

@TomPeters
Issue body actions

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.

Reactions are currently unavailable

Metadata

Metadata

Assignees

Labels

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

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions

    Morty Proxy This is a proxified and sanitized view of the page, visit original site.