简体   繁体   English

如何在打字稿上使用linq js总和和平均值?

[英]How to use linq js sum and average on typescript?

I am trying to use Linq js library on the typescript. 我正在尝试在打字稿上使用Linq js库。 I have the following function; 我有以下功能;

 calculateAvgRating(data) {
        this.user_ratings = Enumerable.from(data).groupBy(p => '${p.rating_type}', null,
            function (key, g) {
                var result = {
                    rating_type: key,
                    total: g.sum("$.rating"),
                    avg: g.average("$.rating")
                }
                return result;
            }).toArray();
    }

However, the lines where I am calculating the total and average are giving me the following typescript error; 但是,我计算总和平均值的行给了我以下打字错误:

Argument of type 'string' is not assignable to parameter of type '(element: {}) => number'. 类型'string'的参数不能分配给类型'(element:{})=> number'的参数。

I know, I need to change the parameter that I am giving to sum and average functions but I couldn't figure it out. 我知道,我需要更改为求和和平均函数提供的参数,但我无法弄清楚。

It seems like the definition file for the linq.js library does not support the shorthand ( op.sum("$.value | 0") ), although the library does. 似乎linq.js库的定义文件不支持速记( op.sum("$.value | 0") ),尽管该库支持。

You can either exclude the ts compiler from prompting an error on the library, which is not ideal, or use function callbacks. 您可以将ts编译器排除在库错误提示之外,这不是很理想,也可以使用函数回调。

import { from } from 'linq';

interface IRating {
    type: number,
    value: number
};

let data: IRating[] = [{
    type: 5,
    value: 5.0
}, {
    type: 0,
    value: 1.0
}, {
    type: 3,
    value: 2.3
}, {
    type: 0,
    value: 0.6
}];


let result = from(data).groupBy(rating => rating.type, null, (key, op) => {
    return {
        type: key,
        total: op.sum(item => item["value"] || 0),
        avg: op.average(item => item["value"] || 0)
    };
}).toArray();

console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM