We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
sum
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)
The text was updated successfully, but these errors were encountered:
types: type safer implementation for sum (sodiray#358)
0816acc
types: type safer implementation for sum function (#358) (#359)
94d43e7
* types: type safer implementation for `sum` (#358) * fix checks --------- Co-authored-by: jukanntenn <jukanntenn@outlook.com>
961fc75
Successfully merging a pull request may close this issue.
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:The text was updated successfully, but these errors were encountered: