Reputation: 11864
I need get element in a array by key.
const legendColors = {'On Hold': '#ef2e2e', 'Shipped': '#ff8e28', 'Complete': '#61c673', 'New': '#007cbb'};
...
return {name: v.name, value: v.value, color: legendColors[v.name]};
lint tool return this error on 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.
Upvotes: 1
Views: 48
Reputation: 32146
Typescript complains because there is no guarantee that v.name
is one of the keys of legendColors
, and there is no index signature. You can get past this by giving typescript a hint that v.name
is in fact one of the keys:
return {name: v.name, value: v.value, color: legendColors[v.name as keyof typeof legendColors]};
or if legendColors adheres to an interface you already know the name of, you can simplify that a little:
return {name: v.name, value: v.value, color: legendColors[v.name as keyof SomeInterface]};
Finally, if you're actually not sure if v.name
is a key of legendColors, then you'll actually have to add an index signature to it.
const legendColors: {[key: string]: string} = {'On Hold': '#ef2e2e', 'Shipped': '#ff8e28', 'Complete': '#61c673', 'New': '#007cbb'};
Upvotes: 2