Repository navigation
Array.reduce doesn't work Β #44063
Description
Activity
The example code should be here as plain text, and phrases like "doesn't work" and "works" aren't really descriptive enough to do anybody much good. Could you make an edit?
Note that this seems to be a duplicate of or strongly related to #36390; that issue is closed as fixed, although the problem with
reduce()remains; not sure if this one should stay open in its place or if there's a different canonical issue somewhere.Reacted by Artem Ilchenko and Vas SudanaguntaReacted by Martin Johns- addedUnactionableThere isn't something we can do with this issueThere isn't something we can do with this issue
on May 12, 2021 RyanCavanaugh commented
on May 12, 2021 MemberMore actionsI think what you want is this (which has two edits)
TEST_LIST.map((testListItem) => { const options = testListItem.options; (options as IBaseOption[]).reduce<ValueType[]>((acc, option) => { if(option.parentValue) { acc.push(option.parentValue) } return acc; }, []); })
There's no typesafe way for TS to collapse the different
reducedefinitions without knowing whatreduce"actually does"; requiring a type assertion here is appropriate.But one question reading comments above: considering options as
IBaseOption[] | ISelectOption[]I expect to get type for option inside reduce likeIBaseOption | ISelectOptionand at the same timenever[]for accum before setting type via generic. am I right?Reacted by Artem IlchenkoI poked around in the files of #31023, which fixed .map() on unions of array types (closing #36390), and found this comment in the test suite:
which indicates that .reduce() not working was a known limitation. Wesley Wigham (@weswigham) β any chance you already have an issue tracking that somewhere, or is this ticket fine? I've also checked some other common array methods and created a new issue to track the ones that aren't working.
Reacted by Artem Ilchenko, Sergiu Bologa and Jimmy WilsonReacted by Dzmitry Koutun, Joo Hee Paige Kim, ciprian1992 and Artem IlchenkoThis issue has been marked as 'Unactionable' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
Bug Report
π Search Terms
Array.reduce
Array.reduce doesn't work
π Version & Regression Information
β― Playground Link
Playground link with relevant code
π» Code
π Actual behavior
TS throws error "This expression is not callable."
π Expected behavior
TS should let me iterate through array (I tell it the type is either array of IBaseOption OR array of ISelectOption (not an array of mixed types). In any case the variable is an array and those methods should be callable.