You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How does TypeScript infer the type of the accumulator in reduce()?
TypeScript infers the type of the accumulator based on the initial value provided (if any) and the return type of the reducer function. If no initial value is provided, it infers the type from the first element of the array. https://www.geeksforgeeks.org/typescript-array-reduce-method/
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered:
I believe this is working as intended. reduce() has several overloads, and the one used does not have an additional type argument for the initialValue because the provided value is compatible with your array type.
A workaround is to explicitly choose the overload with the type argument by providing it: numbersArray.reduce<number>(...)
🔎 Search Terms
"reduce initial value", "wrong inferred initial value in reduce"
🕗 Version & Regression Information
⏯ Playground Link
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBGCuBbARgUwE4QILvQQwE8YBeGAbQEYAaGeMAE1QDMBLMVemgJhoGYa6jVu04wArAF0AsAChZAG1Sw2LKCzzyAahvioAXHCRp0JGAAZZs0JFgQkiPOiKkEKDNlyEAdOg7xgqAAUgXjAwDQAbjqoAJQkAHwwAN6yMGkwvlDw6GAwocAwANQwgVHyujAA-JXmMbIAvjQqahra5bFAA
💻 Code
🙁 Actual behavior
acc
isnumber | undefined
instead ofnumber
🙂 Expected behavior
Since an
initialValue
is provided the type ofacc
should be inferred from it and not from the first element of thenumbersArray
.Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: