为 lodash reduce 指定对象类型

Specify object type for lodash reduce

Lodash _.reduce() 将接受一个对象,但我收到一个 TypeScript 错误(在下面评论),表明它需要一个数组。如何正确设置此示例中的类型?

interface Fees {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees: Fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;

// Argument of type 'Fees' is not assignable to parameter of type 'NumericDictionary'.
// Index signature is missing in type 'Fees'.
total += _.reduce(fees, (sum: number, v: number) => sum + v, 0);

不幸的是,因为您将费用类型定义为 Fees,它不再被视为 Object,因为 TypeScript's structural typing 它会通过 NumericDictionary<T> 的检查.

所以你基本上有两个选择。

1) 从fees 变量中删除类型声明。无论如何都不需要声明类型。 TypeScript 将为您推断类型,稍后当您将对象传递到需要 Fees 实例的地方时,它将通过,因为结构类型(基本上是鸭子类型)。

interface Fees {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;
total += _.reduce(fees, (sum, v) => sum + v, 0);

2) 将费用声明为 NumericDictionary<number>

的扩展
interface Fees extends _.NumericDictionary<number> {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees: Fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;    
total += _.reduce(fees, (sum, v) => sum + v, 0);

顺便说一句,你不需要在reduce函数中声明sumv的类型,这是从fees的类型推断出来的。