Skip to content

Assingment type inference is broken with map, forEachΒ #61755

Closed
@pakettiale

Description

@pakettiale

πŸ”Ž Search Terms

"union narrowing", "map", "forEach"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type inference and narrowing

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=3.3.3#code/DYUwLgBAhgXBB2BXAtgIxAJwgHwY4wEAvHgQNwBQFUlFA2gIwA0EATCwMwC6AdAGYB7DAFEoAYwAWACnjEAfBADeFCKujEIDSgF8AlFRpVBWKWIHwAzpAAeEAXwiMm7brqUq1UDVoraDlIA

πŸ’» Code

let a: number | null = null;

a;

[1, 2, 3].forEach(n => {
    a = 1;
})

a;

for (const x of [1,2,3]) {
    a = 1;
}

a;

πŸ™ Actual behavior

Variable a on line 9 is inferred as null even though it is assigned a number value in forEach

πŸ™‚ Expected behavior

Expect it to be inferred as number | null or preferably number.

On line 15 it is demonstrated that after for (const x of xs) { a = 1; } the type of a is inferred as number | null. I would expect map and forEach to follow the same logic.

Additional information about the issue

This can be worked around by defining a on line 1 like this

const a = null as null | number;

Now a is inferred as number | null in both cases

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions