Closed
Description
π 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
π» 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
Labels
No labels