-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Poor type inference for reduce
#25454
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
I think this goes here:
Error: Expected result is no error. We should be allowed to reduce an object to a single value that isn't the same object without using an initializer. |
@willyboy It's indicating a bug in your code. You're not passing an intial value into TypeScript says that you have Check out this snippet for comparison. |
I can add something to this. I have an array with The
|
I have a similar issue: const recordArray: Record<string, any>[] = [
{ 'a': 1, 'b': 'B', 'c': [1, 2, 3] },
{ 'd': 4, 'e': 'E', 'f': [4, 5, 6] },
{ 'g': 7, 'h': 'H', 'i': [7, 8, 9] }
];
const reducedArray = recordArray.reduce(
(map, record) => map,
new Map<string, string>()
); In this code If The example above is a pretty stupid example but I think it shows the issue pretty well. My real code looks more like the following: const reducedArray = recordArray.reduce(
(map, record) => condition
? map.set(...)
: map,
new Map<...>()
); Edit: The example below is actually a simple and useful example. It converts a const record: Record<string, any>[] = ...
const map = record.reduce(
(acc, item, index) => acc.set(index, item.property),
new Map<number, any>()
); In this example the expected types for Again the interesting part is that it seems to work as long as |
@Vulcagon You can work around this problem by typing the accumulator in the callback: const reducedArray = recordArray.reduce(
(map: Map<string, string>, record) => map,
new Map<string, string>()
); But I agree that this should be considered a bug and fixed! When an initial value is passed into |
TypeScript Version: 3.0.0-dev.20180705
Code
Expected behavior:
No error.
Actual behavior:
No error if
arr
isReadonlyArray<number>
or some other non-object
type.No error if I explicitly specify
arr.reduce<string[]>
.No error if I remove the first two overloads to
reduce
, which are non-generic.The text was updated successfully, but these errors were encountered: