2016-11-24 8 views
1

Lodash _.reduce()はオブジェクトを受け取りますが、配列が必要であることを示すTypeScriptエラーが表示されます。この例では、どのようにタイプを正しく設定するのですか?あなたはFeesとして手数料の種類を定義しているため残念ながら、それはもはやためTypeScript's structural typingNumericDictionary<T>のチェックを通過するObjectを、扱われlodashのオブジェクトタイプを指定してください。

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

私はこのタイプコードを知らないが、このコードは動作する:total + = _.duduce(fee、function(acc、v){ \t return acc + v; }、0); 多分このパッケージはhttps://www.npmjs.com/package/@types/lodash – stasovlas

答えて

2

基本的に2つのオプションがあります。

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

の拡張として手数料を宣言し、方法によって、あなたは減らす機能でsumvの種類を宣言する必要はありませんから、inferedされますタイプはfeesです。

関連する問題