2017-11-21 25 views
1

キーで配列内の要素を取得する必要があります。角2 TypeScript配列の要素を取得する方法

const legendColors = {'On Hold': '#ef2e2e', 'Shipped': '#ff8e28', 'Complete': '#61c673', 'New': '#007cbb'}; 

...

return {name: v.name, value: v.value, color: legendColors[v.name]}; 

リントツールlegendColors[v.name]にこのエラーを返す:

ERROR in src/app/pages/orders/orders.composant.ts(46,62): error TS7017: Element implicitly has an 'any' type because type '{ 'On Hold': string; 'Shipped': string; 'Complete': string; 'New': string; }' has no index signature. 

答えて

2

v.namelegendColorsの鍵の一つであるという保証はありませんので、活字体は、不平を言うとインデックス署名はありません。

return {name: v.name, value: v.value, color: legendColors[v.name as keyof typeof legendColors]}; 

またはlegendColorsもしあなたはすでにあなたがその少しを簡素化することができます、の名前を知っているインタフェースに準拠:

あなたはtypescriptですに v.nameが実際に鍵の一つであるというヒントを与えることによって、この乗り越えることができます
return {name: v.name, value: v.value, color: legendColors[v.name as keyof SomeInterface]}; 

最後に、実際にがlegendColorsのキーであるかどうかわからない場合は、実際にインデックスの署名を追加する必要があります。

const legendColors: {[key: string]: string} = {'On Hold': '#ef2e2e', 'Shipped': '#ff8e28', 'Complete': '#61c673', 'New': '#007cbb'}; 
関連する問題