Skip to content
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

Type safer implementation for sum function #358

Closed
jukanntenn opened this issue Oct 18, 2023 · 0 comments · Fixed by #359
Closed

Type safer implementation for sum function #358

jukanntenn opened this issue Oct 18, 2023 · 0 comments · Fixed by #359

Comments

@jukanntenn
Copy link
Contributor

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)
jukanntenn pushed a commit to jukanntenn/radash that referenced this issue Oct 18, 2023
sodiray pushed a commit that referenced this issue Feb 21, 2024
* types: type safer implementation for `sum` (#358)

* fix checks

---------

Co-authored-by: jukanntenn <jukanntenn@outlook.com>
aleclarson referenced this issue in radashi-org/radashi Jun 24, 2024
* types: type safer implementation for `sum` (#358)

* fix checks

---------

Co-authored-by: jukanntenn <jukanntenn@outlook.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant