Skip to content

union of function types should be narrowed by their return typeΒ #49968

@DetachHead

Description

@DetachHead

Bug Report

πŸ”Ž Search Terms

narrow function types by return type

πŸ•— Version & Regression Information

4.8.0-dev.20220719

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

declare let f1: (() => number) | (() => string)
declare let f2: () => (number | string)

if (typeof f1() === 'string') {
    const foo: string = f1() //should be narrowed to string but isn't
}

if (typeof f2() === 'string') {
    const foo: string = f2() //correctly not narrowed
}

f1 = f2 //correct error

πŸ™ Actual behavior

f1 is not narrowed to () => string

typescript does seem to recognize that the two types () => (number | string) and (() => number) | (() => string)
are different though, as it does not allow assigning f2 to f1

πŸ™‚ Expected behavior

f1 is narrowed to () => string, as the union type (() => number) | (() => string) means that the function either only ever returns a string or only ever returns a number. so if the first function call returns a string it's safe to say that subsequent calls will also return a string

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions