Initializer type defined as a utility type in reduce works but type assertion and type inference fail.
Should there be any difference between specifying the type in the initializer, the reduce return type, or type asserting the return of the reduce?
Why does the type inference fail here? Shouldn’t specifying the type anywhere have the same effect?
Code:
const sequenceFrequency = {a: 3, b: 5, c: 1};
console.log(Object
.entries(sequenceFrequency)
.reduce<[number, string]>(([maxFrequency, maxSequence], [sequence, frequency]) =>
frequency > maxFrequency ? [frequency, sequence ] : [maxFrequency, maxSequence]
, [0, ""])
);
console.log(Object
.entries(sequenceFrequency)
.reduce(([maxFrequency, maxSequence], [sequence, frequency]) =>
frequency > maxFrequency ? [frequency, sequence ] : [maxFrequency, maxSequence]
, [0, ""]) as [number, string]
);
I’ve read this and this and they should be the same from what I could gather.
Error code
console.log(Object
.entries(sequenceFrequency)
.reduce(([maxFrequency, maxSequence], [sequence, frequency]) =>
frequency > maxFrequency ? [frequency, sequence ] : [maxFrequency, maxSequence]
, [0, ""] as [number, string])
);
No overload matches this call.
console.log(Object
.entries(sequenceFrequency)
.reduce(([maxFrequency, maxSequence], [sequence, frequency]) =>
frequency > maxFrequency ? [frequency, sequence ] : [maxFrequency, maxSequence]
, [0, ""])
);
Operator '>' cannot be applied to types 'number' and 'string | number'.(2365)
Playground Link.
1