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
constA: Record<string,number|null>={};constsum1=Object.values(A).reduce((sum)=>sum+1,0);// ^ error: 'sum' is possibly 'null'// no errors with string in initialValueconstsum2=Object.values(A).reduce((sum)=>sum+1,'');
π Actual behavior
TypeScript incorrectly infers the type of the accumulator in the reduce method as number | null even when the initial value is number.
π Expected behavior
TypeScript should infer the type of the accumulator the reduce method as number when the initial value is a number.
Additional information about the issue
Explicitly specifying the types resolves the issue, but TypeScript should correctly infer the type without explicit types.
constA: Record<string,number|null>={};constsum1=Object.values(A).reduce((sum: number)=>sum+1,0);// ^^^^^^ ^ no errors
The text was updated successfully, but these errors were encountered:
It doesn't look like reduce itself is generic. The point of inference is Object.values where it infers T as number | null from Record<string, number | null>, which is correct.
Correction: I missed the third overload, which is generic. It looks like that overload is not being selected here. Probably the first overload (non-generic) is being selected since your arguments are all valid subtypes of the parameter types.
The error goes away if you explicitly call the generic overload.
Probably the first overload (non-generic) is being selected since your arguments are all valid subtypes of the parameter types.
That's what's going on. I think the ordering priority of the overloads is justified. If you call reduce with an initialValue that is compatible with the element type of the array, isn't it more likely that you want that element type and not a subtype?
One can easily devise examples of reasonable-looking operations that fail if the overloads are switched: Playground
π Search Terms
incorrect type inference for reduce
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?#code/MYewdgzgLgBAggLhgJQKagE4BMA80MCWYA5gDQxgCuAtgEaoYwA+FlANmwHwwC8MA3gF8A3AChQkWBBoBGXjADytAFbooAOgBuAQzaVUEABRwAlOoyoslYKkOHp1E724OYAahgzyABhNjRAPQBFCAwDBggGBAwAO4EUAAWMPhExDBE6WDxBLoAarr64uDQyTQATPJKqsAaOnoGxmYWVjZ2Dk48LjTunuQA5H1+okA
π» Code
π Actual behavior
TypeScript incorrectly infers the type of the accumulator in the
reduce
method asnumber | null
even when the initial value is number.π Expected behavior
TypeScript should infer the type of the accumulator the
reduce
method asnumber
when the initial value is a number.Additional information about the issue
Explicitly specifying the types resolves the issue, but TypeScript should correctly infer the type without explicit types.
The text was updated successfully, but these errors were encountered: