Skip to content

Type narrowing context is lost within closuresΒ #46118

Description

@ramyhhh

Bug Report

πŸ”Ž Search Terms

typescript union typed narrowing lost in closures
type narrowing closures

πŸ•— Version & Regression Information

Typescript versions 4.4.3 and still exists on Nightly 4.5.0-dev

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type MyUnion = { type: 'left', propertyExistsOnLeft: string } | { type: 'right', propertyExistsOnRight: string }

let x = {} as MyUnion;

switch (x.type) {
    case 'left':
        const y = x.propertyExistsOnLeft; //all good here ...
        console.log(() => x.propertyExistsOnLeft) //showing error "Property 'propertyExistsOnLeft' does not exist on type 'MyUnion'"
        break;
}

πŸ™ Actual behavior

Type narrowing is working as expected when following control flow, however when the variable is used inside a closures scope (arrow functions or normal functions) it reverts back to it's declared type losing all narrowing inferred from the containing scope.

πŸ™‚ Expected behavior

Type narrowing should continue to work inside the context of closures.

Activity

  1. changed the title [-]Type narrowing lost within closures[/-] [+]Type narrowing context is lost within closures[/+] on Sep 28, 2021
  2. MartinJohns commented on Sep 28, 2021

    @MartinJohns
    Contributor

    And another duplicate of #9998.

  3. ramyhhh commented on Sep 28, 2021

    @ramyhhh
    Author

    Yeah, that issue looks like a master issue collecting all control flow analysis issues :)

  4. MartinJohns commented on Sep 28, 2021

    @MartinJohns
    Contributor

    The exact same issue you describe comes up again and again and again. I probably have seen at least 50 issues already. It's all due to the difficulties described in #9998.

  5. fatcerberus commented on Sep 28, 2021

    @fatcerberus

    Yeah, that issue looks like a master issue collecting all control flow analysis issues :)

    More specifically, control flow analysis issues across function boundaries. Which is not an easy problem to solve.

  6. typescript-bot commented on Oct 3, 2021

    @typescript-bot
    Contributor

    This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

  7. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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