1

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.

1 Answer 1

2

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'};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.