Skip to content

Narrowed variable types become widened in functions defined after narrowing #50580

Closed
@mattrunyon

Description

@mattrunyon

Bug Report

🔎 Search Terms

possibly undefined array methods predicate mutable variables narrowing

🕗 Version & Regression Information

4.5.4

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about functions and method "bugs" that aren't bugs

⏯ Playground Link

Playground link with relevant code

💻 Code

function test(param?: number): number {
    let a: number | undefined;

    // Some code that could make a defined goes here

    if (a === undefined || param === undefined) {
        return 0;
    }

    const b = () => a + param; // a is not narrowed. param is narrowed

    function c() {
        // Neither is narrowed
        return a + param;
    }

    [1, 2, 3].map(elem => elem + a + param); // a is not narrowed

    return a + param; // Both narrowed
}

🙁 Actual behavior

The variables are not narrowed when used in functions. param is narrowed when using an arrow function. This causes friction when trying to use an array method that takes a function as an argument

🙂 Expected behavior

Both variables are narrowed to number in all cases

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