为lodash reduce指定对象类型

时间:2016-11-24 15:53:19

标签: typescript lodash typescript-typings

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);

1 个答案:

答案 0 :(得分:2)

不幸的是,由于您将费用类型定义为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的类型。