Skip to content

The type returned by Array.prototype.find() is not narrowedΒ #53488

@exoRift

Description

@exoRift

Bug Report

πŸ”Ž Search Terms

.find
narrow find

πŸ•— Version & Regression Information

5.0.2

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Foo = {
    discriminator: 'bar',
    value: number
} | {
    discriminator: 'baz',
    value: string
}

function assertString (param: string) {}
function assertNumber (param: number) {}

function func (param: Foo[]) {
    const found = param.find((p) => p.discriminator === 'bar')

    if (!found) return

    assertNumber(found.value) // < issue

    if (found.discriminator === 'bar') assertNumber(found.value) // < no problem
}

πŸ™ Actual behavior

The find does not narrow the returned type

πŸ™‚ Expected behavior

The logical flow SHOULD narrow it. Typescript IS capable of this. I understand the check is in another scope, but can't it be propagated upwards?

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