sodiray / radash

Functional utility library - modern, simple, typed, powerful
https://radash-docs.vercel.app
MIT License
4.18k stars 167 forks source link

Type safer implementation for `sum` function #358

Closed jukanntenn closed 6 months ago

jukanntenn commented 11 months ago

Current type declaration of sum function is not type safe, for example:

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)