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);
答案 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函数中声明sum
和v
的类型,这类型来自fees
的类型。