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]
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With