-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Array.forEach incorrectly narrows the inferred type when elements are annotated with union type #55201
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
Comments
Subtype reduction, working as intended. |
Essentially a duplicate of #46449 and many others: if |
Essentially a restatement of #53425 (comment), fwiw |
@jcalz @fatcerberus thanks for the explanation, but why this is not an issue with
I agree in general based on typescript not being "a perfectly sound system", however this did feel like a bug in our use case: we were using https://typescript-eslint.io/ to lint the data usage based on the type information, and when a piece of data was transformed with Array#forEach it produced wrong result due to this sub type reduction behavior. |
This issue has been marked as "Not a Defect" and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
Bug Report
π Search Terms
Array.forEach
union type
π Version & Regression Information
all versions
β― Playground Link
Playground link with relevant **code**
π» Code
π Actual behavior
The inferred type of

value
is simplyFooValue
:π Expected behavior
But really it should be

FooValue | BarValue
, which is correct when using.map
:I suspect this issue happens because
forEach
isn't annotated with generic return typeU
whilemap
is:TypeScript/src/lib/es5.d.ts
Lines 1235 to 1246 in 250065e
In fact after changing

forEach
toforEach<U>
fixes this problem locally:The text was updated successfully, but these errors were encountered: