【问题标题】:Specify object type for lodash reduce为 lodash reduce 指定对象类型
【发布时间】:2016-11-24 15:53:18
【问题描述】:

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

【问题讨论】:

  • 我不知道打字稿,但这段代码有效:total += _.reduce(fees, function(acc, v) { return acc + v; }, 0);也许这个包可以帮助npmjs.com/package/@types/lodash

标签: typescript lodash typescript-typings


【解决方案1】:

不幸的是,因为您将费用类型定义为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的类型推断出来的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2015-11-06
    相关资源
    最近更新 更多