Closed jukanntenn closed 6 months ago
Current type declaration of sum function is not type safe, for example:
sum
sum([{"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 1, "b": 2}])
does not trigger a type error.
I propose a type safer implementation for sum function using function overload:
export function sum<T extends number>(array: readonly T[]): number; export function sum<T extends object>(array: readonly T[], fn: (item: T) => number) : number; export function sum <T extends object | number>(array: readonly any[], fn?: (item: T) => number): number { return (array || []).reduce( (acc, item) => acc + (fn ? fn(item) : item), 0 ) } sum([{"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 1, "b": 2}]) // Type '{ a: number; b: number; }' is not assignable to type 'number'.ts(2322)
Current type declaration of
sum
function is not type safe, for example:does not trigger a type error.
I propose a type safer implementation for
sum
function using function overload: