Skip to content

Assingment type inference is broken with map, forEach #61755

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pakettiale opened this issue May 22, 2025 · 1 comment
Closed

Assingment type inference is broken with map, forEach #61755

pakettiale opened this issue May 22, 2025 · 1 comment

Comments

@pakettiale
Copy link

πŸ”Ž 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

@pakettiale
Copy link
Author

This is duplicate of #9998

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant