Skip to content

Adding boolean type assertion changes type narrowing  #60190

Description

@jauwesome

🔎 Search Terms

Type Narrowing
Boolean
Undefined

🕗 Version & Regression Information

Version: 5.6.3
Regression: Unknown

⏯ Playground Link

https://www.typescriptlang.org/play/?noUnusedLocals=true&noUnusedParameters=true#code/GYVwdgxgLglg9mABFApgZygeTCgFMOOALkQwCcYwBzRAH0XABMVhKVGBKRAbwChEBiCAgzIAFpRoBeRAEJZBOAG5+gmMFxQJ1Ln0H7EZFFBBkkigHQQxAQzIBBKLgAMHFfoC+qgUZNnEAORMLGyMAbxevKCQsAjI6FAAKgDucPiEJOSSdAxgzKw4nDzeQiJQ4pIkAEaEADYoNkgy8oruahpakrol+r6m5oRWtg5Orm0CXr3G-YHBBezhHkA

💻 Code

function testOne(foo: string | undefined) {
    const thing = !!foo;
    if(thing) {
        // Foo type is String
        return foo.charAt(0);
    }
    return 'undefined'
}

function testTwo(foo: string | undefined) {
    const thing: boolean = !!foo;
    if(thing) {
         // Foo type is string | undefined
        return foo.charAt(0);
    }
    return 'undefined'
}

🙁 Actual behavior

foo is typed as string | undefined if thing has explicit type of boolean

🙂 Expected behavior

foo should be typed as string if thing has type of boolean just like if thing's type is inferred

Additional information about the issue

No response

Activity

  1. changed the title [-]Adding boolean type assertion changes type narrowing for undefined[/-] [+]Adding boolean type assertion changes type narrowing [/+] on Oct 10, 2024
  2. RyanCavanaugh commented on Oct 10, 2024

    @RyanCavanaugh
    Member

    This was an intentional boundary in #44730

  3. jauwesome commented on Oct 10, 2024

    @jauwesome
    Author

    Ryan Cavanaugh (@RyanCavanaugh) Thanks for the quick response! Is there a specific reason why this choice was made? I don't see that listed. Regardless we can close the ticket.

  4. RyanCavanaugh commented on Oct 10, 2024

    @RyanCavanaugh
    Member

    IIRC it's possible to get into a type resolution circularity with this inference in a way that wouldn't really be solvable, so you need some "out" in cases where you're not using it for narrowing purposes

  5. jauwesome commented on Oct 11, 2024

    @jauwesome
    Author

    Good to know! That makes sense. Thanks again for your help!

  6. locked as resolved and limited conversation to collaborators on Oct 22, 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

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions