Skip to content

Adding boolean type assertion changes type narrowing Β #60190

Closed
@jauwesome

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

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