Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

Let's say I have this:

const color = {     red: null,     green: null,     blue: null };  const newColor = ['red', 'green', 'blue'].filter(e => color[e]); 

The error is in color[e] near the bottom with:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ red: null; green: null; blue: null; }'. No index signature with a parameter of type 'string' was found on type '{ red: null; green: null; blue: null; }'.

I tried looking everywhere on TypeScript docs, but how the heck am I suppose to interface this so it can accept color[e]?

like image 712
test Avatar asked Aug 09 '19 23:08

test


People also ask

How do you fix element implicitly has an any type because expression of type string can't be used to index type?

The error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type" occurs when we use a string to index an object with specific keys. To solve the error, type the string as one of the object's keys.

Has an any type because index expression is not of type number?

The error "Element implicitly has 'any' type because index expression is not of type 'number'" occurs when an array is indexed with a value that is not a number. To solve the error, use an object if storing key-value pairs or use a type assertion.

Is not assignable to type string?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.

Does not exist on type TypeScript?

The "Property does not exist on type '{}'" error occurs when we try to access or set a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.


Video Answer


1 Answers

You can declare colors as any to tell TypeScript to get off your back on this one (aka explicit any):

const color : any = {     red: null,     green: null,     blue: null }; 

But if possible, strong typing is preferable:

const color : { [key: string]: any } = {     red: null,     green: null,     blue: null }; 

More information on indexing in TypeScript: Index Signatures


EDIT: In this answer to a similar question, the author suggest using a Map<,> -- if that fits your use-case.

like image 156
hugo Avatar answered Oct 11 '22 22:10

hugo