Hello Guys, How are you all? Hope You all Are Fine. Today I am facing Following error TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type in Javascript. So Here I am Explain to you all the possible solutions here.
Without wasting your time, Let’s start This Article to Solve This Error.
How TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type Error Occurs ?
I Have this code.
const sub = {
science: null,
social: null,
math: null
};
const newColor = ['science', 'social', 'math'].filter(e => sub[e]);
But I am facing this error.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ science: null; social: null; math: null; }'. No index signature with a parameter of type 'string' was found on type '{ science: null; social: null; math: null; }'.
How To Solve TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type Error ?
- How To Solve TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type Error?
To Solve TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type Error The as const causes the compiler to infer a tuple composed of exactly the three string literals in the array, in the exact order you’ve set. (It’s even a read-only tuple). That is good enough to fix your error:
- TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type
To Solve TypeScript – Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type Error The as const causes the compiler to infer a tuple composed of exactly the three string literals in the array, in the exact order you’ve set. (It’s even a read-only tuple). That is good enough to fix your error:
Solution 1
You can declare sub
as any
to tell TypeScript to get off your back on this one (aka explicit any):
const sub : any = {
science: null,
social: null,
math: null
};
But if possible, strong typing is preferable:
const sub : { [key: string]: any } = {
science: null,
social: null,
math: null
};
Solution 2
Assuming you’re using TS3.4 or later, the easiest way to get this kind of type inference from the compiler is to use an const
assertion:
const constAssertionTest = ["science", "social", "math"] as const;
The as const
causes the compiler to infer a tuple composed of exactly the three string literals in the array, in the exact order you’ve set. (It’s even a read-only tuple). That is good enough to fix your error:
const newColor = (["science", "social", "math"] as const).filter(e => sub[e]); // this is fine
Summery
It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you?
Also Read